Class: Bitcoin::Wallet::DB

Inherits:
Object
  • Object
show all
Defined in:
lib/bitcoin/wallet/db.rb

Constant Summary collapse

KEY_PREFIX =
{
    account: 'a',       # key: account index, value: Account raw data.
    master: 'm',        # value: wallet seed.
    version: 'v',       # value: wallet version
    key: 'k',           # key: path to the key, value: public key
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = "#{Bitcoin.base_dir}/db/wallet") ⇒ DB

Returns a new instance of DB.



16
17
18
19
# File 'lib/bitcoin/wallet/db.rb', line 16

def initialize(path = "#{Bitcoin.base_dir}/db/wallet")
  FileUtils.mkdir_p(path)
  @level_db = ::LevelDBNative::DB.new(path)
end

Instance Attribute Details

#level_dbObject (readonly)

Returns the value of attribute level_db.



13
14
15
# File 'lib/bitcoin/wallet/db.rb', line 13

def level_db
  @level_db
end

#master_keyObject

get master_key



57
58
59
# File 'lib/bitcoin/wallet/db.rb', line 57

def master_key
  @master_key
end

Instance Method Details

#accountsObject

get accounts raw data.



27
28
29
30
31
# File 'lib/bitcoin/wallet/db.rb', line 27

def accounts
  from = KEY_PREFIX[:account] + '00000000'
  to = KEY_PREFIX[:account] + 'ffffffff'
  level_db.each(from: from, to: to).map { |k, v| v}
end

#closeObject

close database



22
23
24
# File 'lib/bitcoin/wallet/db.rb', line 22

def close
  level_db.close
end

#get_keys(account) ⇒ Object



49
50
51
52
53
54
# File 'lib/bitcoin/wallet/db.rb', line 49

def get_keys()
  id = [.purpose, .index].pack('I*').bth
  from = KEY_PREFIX[:key] + id + '00000000'
  to = KEY_PREFIX[:key] + id + 'ffffffff'
  level_db.each(from: from, to: to).map { |k, v| v}
end

#register_master_key(master) ⇒ Object

save seed

Parameters:



63
64
65
66
67
# File 'lib/bitcoin/wallet/db.rb', line 63

def register_master_key(master)
  level_db.put(KEY_PREFIX[:master], master.to_payload)
  level_db.put(KEY_PREFIX[:version], Bitcoin::Wallet::Base::VERSION.to_s)
  @master_key = master
end

#registered_master?Boolean

whether master key registered.

Returns:

  • (Boolean)


70
71
72
# File 'lib/bitcoin/wallet/db.rb', line 70

def registered_master?
  !level_db.get(KEY_PREFIX[:master]).nil?
end

#save_account(account) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/bitcoin/wallet/db.rb', line 33

def ()
  level_db.batch do
    id = [.purpose, .index].pack('I*').bth
    key = KEY_PREFIX[:account] + id
    level_db.put(key, .to_payload)
  end
end

#save_key(account, purpose, index, key) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/bitcoin/wallet/db.rb', line 41

def save_key(, purpose, index, key)
  pubkey = key.pub
  id = [.purpose, .index, purpose, index].pack('I*').bth
  k = KEY_PREFIX[:key] + id
  level_db.put(k, pubkey)
  key
end

#versionObject

wallet version



75
76
77
# File 'lib/bitcoin/wallet/db.rb', line 75

def version
  level_db.get(KEY_PREFIX[:version]).to_i
end