-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathwallet.rb
72 lines (55 loc) · 1.94 KB
/
wallet.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Wallet
def initialize(private_key)
@private_key = private_key
end
def public_key
pk = group.generator.multiply_by_scalar(@private_key)
pk_string = ECDSA::Format::PointOctetString.encode(pk, compression: true)
Base58.binary_to_base58(pk_string)
end
# The destination address is just the public key hashed. It provides the
# advantage of having destination addresses normalized as well as icnreasing
# the level of privacy.
def destination_address
Digest::SHA256.hexdigest(public_key)
end
# Signs a message as a DER string and return it encoded in Base58.
def sign(message)
raise "Only strings can be signed" unless message.is_a?(String)
digest = Digest::SHA256.digest(message)
signature = nil
while signature.nil?
temp_key = 1 + SecureRandom.random_number(group.order - 1)
signature = ECDSA.sign(group, @private_key, digest, temp_key)
end
signature_der_string = ECDSA::Format::SignatureDerString.encode(signature)
Base58.binary_to_base58(signature_der_string)
end
def generate_transaction(destination, amount, fee)
transaction = TransactionBuilder.new(
wallet: self,
)
transaction.set_cryptocurrency_message(destination, amount, fee)
transaction.sign!
transaction
end
private
def group
ECDSA::Group::Secp256k1
end
class << self
def load_or_create(name)
FileUtils.mkdir_p("keys")
group = ECDSA::Group::Secp256k1
# We first try to load an existing private key.
if File.file?("./keys/#{name}.key") == false
private_key = 1 + SecureRandom.random_number(group.order - 1)
File.write("./keys/#{name}.key", Base58.int_to_base58(private_key))
end
# The key doesn't exist, we create a new one and store it for later use.
private_key = File.read("./keys/#{name}.key").to_i
raise "Failed loading the private key" if private_key == 0
Wallet.new(private_key)
end
end
end