-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathweb3.bip32.pas
289 lines (252 loc) · 8.95 KB
/
web3.bip32.pas
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
{******************************************************************************}
{ }
{ Delphereum }
{ }
{ Copyright(c) 2023 Stefan van As <[email protected]> }
{ Github Repository <https://github.com/svanas/delphereum> }
{ }
{ Distributed under GNU AGPL v3.0 with Commons Clause }
{ }
{ This program is free software: you can redistribute it and/or modify }
{ it under the terms of the GNU Affero General Public License as published }
{ by the Free Software Foundation, either version 3 of the License, or }
{ (at your option) any later version. }
{ }
{ This program is distributed in the hope that it will be useful, }
{ but WITHOUT ANY WARRANTY; without even the implied warranty of }
{ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the }
{ GNU Affero General Public License for more details. }
{ }
{ You should have received a copy of the GNU Affero General Public License }
{ along with this program. If not, see <https://www.gnu.org/licenses/> }
{ }
{******************************************************************************}
unit web3.bip32;
interface
uses
// Delphi
System.SysUtils,
// web3
web3,
web3.bip39;
type
IPublicKey = interface
function ToString: string;
end;
IPrivateKey = interface(IPublicKey)
function Data: TBytes;
function NewChildKey(const childIdx: UInt32): IPrivateKey;
function PublicKey: IPublicKey;
end;
IMasterKey = interface(IPrivateKey)
function GetChildKey(const path: string): IResult<IPrivateKey>;
end;
// creates a new master extended key
function master(const seed: web3.bip39.TSeed): IMasterKey;
implementation
uses
// Delphi
System.Character,
System.Classes,
// CryptoLib4Pascal
ClpBigInteger,
ClpBigIntegers,
ClpConverters,
ClpEncoders,
// web3
web3.crypto,
web3.utils;
// the index of the first "hardened" child key
const firstHardenedChild: UInt32 = 2147483648;
// returns the version flag for serialized private keys
function privateWalletVersion: TBytes; inline;
begin
Result := web3.utils.fromHex('0x0488ADE4');
end;
// returns the version flag for serialized public keys
function publicWalletVersion: TBytes; inline;
begin
Result := web3.utils.fromHex('0x0488B21E');
end;
// adds double-sha256 checksum to the data
function addChecksum(const data: TBytes): TBytes; inline;
begin
const digest = sha256(sha256(data));
Result := data + Copy(digest, 0, 4);
end;
function publicKeyFromPrivateKey(const key: TBytes): TBytes; inline;
begin
const params = web3.crypto.privateKeyFromByteArray('ECDSA', SECP256K1, key);
const pubKey = web3.crypto.publicKeyFromPrivateKey(params);
Result := web3.crypto.compressPublicKey(pubKey);
end;
function addPrivateKeys(const key1, key2: TBytes): TBytes;
begin
var int1 := TBigInteger.Create(1, key1);
var int2 := TBigInteger.Create(1, key2);
const curve = web3.crypto.SECP256K1.GetCurve;
int1 := int1.Add(int2);
int1 := int1.&Mod(curve.N);
Result := TBigIntegers.BigIntegerToBytes(int1, 32);
end;
{ TPublicKey }
type
TPublicKey = class(TInterfacedObject, IPublicKey)
private
version : TBytes; // 4 bytes
keyData : TBytes; // 33 bytes
chainCode : TBytes; // 32 bytes
childNumber: TBytes; // 4 bytes
fingerprint: TBytes; // 4 bytes
depth : Byte; // 1 byte
function Serialize: TBytes;
protected
class function isPrivate: Boolean; virtual;
public
constructor Create(const version, keyData, chainCode, childNumber, fingerprint: TBytes; const depth: Byte);
function ToString: string; override;
end;
constructor TPublicKey.Create(const version, keyData, chainCode, childNumber, fingerprint: TBytes; const depth: Byte);
begin
Self.version := version;
Self.keyData := keyData;
Self.chainCode := chainCode;
Self.childNumber := childNumber;
Self.fingerprint := fingerprint;
Self.depth := depth;
end;
class function TPublicKey.isPrivate: Boolean;
begin
Result := False;
end;
// serializes the key to a 78-byte array
function TPublicKey.Serialize: TBytes;
begin
// private keys should be prepended with a single null byte
var keyData := Self.keyData;
if Self.isPrivate then keyData := [0] + keyData;
// write fields in order
Result := Self.version;
Result := Result + [Self.depth];
Result := Result + Self.fingerprint;
Result := Result + Self.childNumber;
Result := Result + Self.chainCode;
Result := Result + keyData;
// append the double-sha256 checksum
Result := addChecksum(Result);
end;
// encodes the key in the standard Bitcoin base58 encoding
function TPublicKey.ToString: string;
begin
Result := TBase58.Encode(Self.Serialize);
end;
type
TPrivateKey = class(TPublicKey, IPrivateKey)
private
function getIntermediary(const childIdx: UInt32): TBytes;
protected
class function isPrivate: Boolean; override;
public
function Data: TBytes;
function NewChildKey(const childIdx: UInt32): IPrivateKey;
function PublicKey: IPublicKey;
end;
{ TPrivateKey }
class function TPrivateKey.isPrivate: Boolean;
begin
Result := True;
end;
function TPrivateKey.Data: TBytes;
begin
Result := Self.keyData;
end;
// derives a child key from a given parent
function TPrivateKey.NewChildKey(const childIdx: UInt32): IPrivateKey;
begin
const intermediary = Self.getIntermediary(childIdx);
Result := TPrivateKey.Create(
privateWalletVersion, // version
addPrivateKeys(Copy(intermediary, 0, 32), Self.keyData), // key data
Copy(intermediary, 32, 32), // chain code
TConverters.ReadUInt32AsBytesBE(childIdx), // child number
Copy(web3.utils.hash160(publicKeyFromPrivateKey(Self.keyData)), 0, 4), // fingerprint
Self.depth + 1 // depth
);
end;
// get intermediary to create keydata and chaincode from
function TPrivateKey.getIntermediary(const childIdx: UInt32): TBytes;
begin
// hardened children are based on the private key, non-hardened children are based on the public key
if childIdx >= firstHardenedChild then
Result := [0] + Self.keyData
else
Result := publicKeyFromPrivateKey(Self.keyData);
Result := Result + TConverters.ReadUInt32AsBytesBE(childIdx);
Result := hmac_sha512(Result, Self.chainCode);
end;
// this is the so-called "neuter" function
function TPrivateKey.PublicKey: IPublicKey;
begin
Result := TPublicKey.Create(
publicWalletVersion, // version
publicKeyFromPrivateKey(keyData), // key data
Self.chainCode, // chain code
Self.childNumber, // child number
Self.fingerprint, // fingerprint
Self.depth // depth
);
end;
type
TMasterKey = class(TPrivateKey, IMasterKey)
public
function GetChildKey(const path: string): IResult<IPrivateKey>;
end;
function TMasterKey.GetChildKey(const path: string): IResult<IPrivateKey>;
begin
const SL = TStringList.Create;
try
SL.Delimiter := '/';
SL.DelimitedText := path;
var K: IPrivateKey := Self;
for var I := 0 to Pred(SL.Count) do
begin
var S := SL[I].Trim;
if (I = 0) and S.Equals('m') then CONTINUE;
var C, E: UInt32; // child, error
Val(S, C, E);
if E <> 0 then
begin
if (S = '') or S[High(S)].IsDigit then
begin
Result := TResult<IPrivateKey>.Err('invalid derivation path');
EXIT;
end;
Delete(S, High(S), 1);
Val(S, C, E);
if E <> 0 then
begin
Result := TResult<IPrivateKey>.Err('invalid derivation path');
EXIT;
end;
C := C + firstHardenedChild;
end;
K := K.NewChildKey(C);
end;
Result := TResult<IPrivateKey>.Ok(K);
finally
SL.Free;
end;
end;
function master(const seed: web3.bip39.TSeed): IMasterKey;
begin
const digest = hmac_sha512(seed, TConverters.ConvertStringToBytes('Bitcoin seed', TEncoding.UTF8));
Result := TMasterKey.Create(
privateWalletVersion, // version
Copy(digest, 0, 32), // key data
Copy(digest, 32, 32), // chain code
[0, 0, 0, 0], // child number
[0, 0, 0, 0], // fingerprint
0 // depth
);
end;
end.