Class: Bitcoin::Wallet::KeyGenerator

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

Overview

Deterministic key generator as described in bitcointalk.org/index.php?topic=11665.0.

Takes a seed and generates an arbitrary amount of keys. Protects against brute-force attacks by requiring the key hash to fit a difficulty target, much like the block chain.

Constant Summary collapse

DEFAULT_TARGET =

difficulty target (0x0000FFFF00000000000000000000000000000000000000000000000000000000)

0x0000FFFF00000000000000000000000000000000000000000000000000000000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(seed = nil, nonce = nil, target = nil) ⇒ KeyGenerator

Initialize key generator with optional seed and nonce and target.

seed

the seed data for the keygenerator (default: random)

nonce

the nonce required to satisfy the target (default: computed)

target

custom difficulty target (default: DEFAULT_TARGET)

Example:

g = KeyGenerator.new # random seed, computed nonce, default target
KeyGenerator.new(g.seed)
KeyGenerator.new(g.seed, g.nonce)
g.get_key(0) #=> <Bitcoin::Key>

Note: When initializing without seed, you should obviously save the seed once it is generated. Saving the nonce is optional; it only saves time.



31
32
33
34
35
# File 'lib/bitcoin/wallet/keygenerator.rb', line 31

def initialize seed = nil, nonce = nil, target = nil
  @seed = seed || OpenSSL::Random.random_bytes(64)
  @target = target || DEFAULT_TARGET
  @nonce = check_nonce(nonce)
end

Instance Attribute Details

#nonceObject

Returns the value of attribute nonce.



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

def nonce
  @nonce
end

#seedObject

Returns the value of attribute seed.



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

def seed
  @seed
end

#targetObject

Returns the value of attribute target.



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

def target
  @target
end

Instance Method Details

#find_nonceObject

find a nonce that leads to the privkey satisfying the target



46
47
48
49
50
# File 'lib/bitcoin/wallet/keygenerator.rb', line 46

def find_nonce
  n = 0
  n += 1  while !check_target(get_hash(@seed, n))
  n
end

#get_key(n = 0) ⇒ Object

get key number n from chain



38
39
40
41
42
43
# File 'lib/bitcoin/wallet/keygenerator.rb', line 38

def get_key(n = 0)
  key = get_hash(@seed, @nonce)
  (n + 1).times { key = sha256(key) }
  key
  Bitcoin::Key.new(key.unpack("H*")[0])
end