-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
web3.eth.crypto.pas
248 lines (213 loc) · 8.04 KB
/
web3.eth.crypto.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
{******************************************************************************}
{ }
{ Delphereum }
{ }
{ Copyright(c) 2018 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.eth.crypto;
{$I web3.inc}
interface
uses
// Delphi
System.SysUtils,
// CryptoLib4Pascal
ClpBigInteger,
ClpBigIntegers,
ClpCryptoLibTypes,
ClpDigestUtilities,
ClpECAlgorithms,
ClpECDomainParameters,
ClpECPublicKeyParameters,
ClpIECC,
ClpIECPublicKeyParameters,
ClpHMacDsaKCalculator,
ClpX9ECC,
// web3
web3,
web3.crypto,
web3.eth,
web3.eth.types,
web3.utils;
type
TEthereumSigner = class(TECDsaSignerEx)
public
constructor Create;
function GenerateSignature(const msg: TCryptoLibByteArray): TECDsaSignature; reintroduce;
end;
TGetRecId = reference to function(const V: TBigInteger): IResult<Int32>;
TSignature = record
private
R: TBigInteger;
S: TBigInteger;
V: TBigInteger;
public
constructor Create(const R, S, V: TBigInteger);
class function FromHex(const hex: string): IResult<TSignature>; static;
function ToHex: string;
end;
function publicKeyToAddress(const pubKey: IECPublicKeyParameters): TAddress;
function sign(const privateKey: TPrivateKey; const msg: string): TSignature; overload;
function sign(const privateKey: TPrivateKey; const raw: TBytes): TSignature; overload;
function ecrecover(const msg: string; const signature: TSignature): IResult<TAddress>; overload;
function ecrecover(const data: TBytes; const signature: TSignature; const getRecId: TGetRecId): IResult<TAddress>; overload;
implementation
function publicKeyToAddress(const pubKey: IECPublicKeyParameters): TAddress;
begin
// take the keccak-256 hash of the public key
var buffer := web3.utils.sha3(publicKeyToByteArray(pubKey));
// take the last 40 characters / 20 bytes of this public key
Delete(buffer, 0, 12);
// hex-encode and prefix with 0x
Result := TAddress.Create(web3.utils.toHex(buffer));
end;
// https://github.com/ethereum/go-ethereum/pull/2940
function pr2940(const msg: string): TBytes;
begin
Result := web3.utils.sha3(
TEncoding.UTF8.GetBytes(
#25 + 'Ethereum Signed Message:' + #10 + IntToStr(TEncoding.UTF8.GetByteCount(msg)) + msg
)
);
end;
// sign message, output Ethereum-specific signature
function sign(const privateKey: TPrivateKey; const msg: string): TSignature;
begin
Result := sign(privateKey, pr2940(msg));
end;
function sign(const privateKey: TPrivateKey; const raw: TBytes): TSignature;
begin
const Signer = TEthereumSigner.Create;
try
Signer.Init(True, privateKey);
const Signature = Signer.GenerateSignature(raw);
const v = Signature.rec.Add(TBigInteger.ValueOf(27));
Result := TSignature.Create(Signature.r, Signature.s, v);
finally
Signer.Free;
end;
end;
// recover signer from Ethereum signed message
function ecrecover(const msg: string; const signature: TSignature): IResult<TAddress>;
begin
Result := ecrecover(pr2940(msg), signature, function(const V: TBigInteger): IResult<Int32>
begin
const B = V.ToByteArrayUnsigned;
if Length(B) = 0 then
begin
Result := TResult<Int32>.Err('V is null');
EXIT;
end;
var I: Int32 := B[0];
if (I < 27) or (I > 34) then
begin
Result := TResult<Int32>.Err('V is out of range');
EXIT;
end;
if I >= 31 then I := I - 4;
Result := TResult<Int32>.Ok(I - 27);
end)
end;
// recover signer from Ethereum-specific signature
function ecrecover(const data: TBytes; const signature: TSignature; const getRecId: TGetRecId): IResult<TAddress>;
function decompressKey(curve: IECCurve; xBN: TBigInteger; yBit: Boolean): IECPoint;
begin
const compEnc = TX9IntegerConverter.IntegerToBytes(xBN, 1 + TX9IntegerConverter.GetByteLength(curve));
if yBit then
compEnc[0] := $03
else
compEnc[0] := $02;
Result := curve.DecodePoint(compEnc);
end;
begin
const recId = getRecId(signature.V);
if recId.isErr then
begin
Result := TResult<TAddress>.Err(recId.Error);
EXIT;
end;
const curve = web3.crypto.SECP256K1.GetCurve;
const n = curve.n;
const prime = curve.Curve.Field.Characteristic;
const i = TBigInteger.ValueOf(Int64(RecId.Value) div 2);
const x = signature.R.Add(i.Multiply(n));
if x.CompareTo(prime) >= 0 then
begin
Result := TResult<TAddress>.Err('an unknown error occurred');
EXIT;
end;
const R = decompressKey(curve.Curve, x, (recId.Value and 1) = 1);
if not R.Multiply(n).IsInfinity then
begin
Result := TResult<TAddress>.Err('an unknown error occurred');
EXIT;
end;
const e = TBigInteger.Create(1, data);
const eInv = TBigInteger.Zero.Subtract(e).&Mod(n);
const rInv = signature.R.ModInverse(n);
const srInv = rInv.Multiply(signature.S).&Mod(n);
const eInvrInv = rInv.Multiply(eInv).&Mod(n);
const q = TECAlgorithms.SumOfTwoMultiplies(curve.G, eInvrInv, R, srInv).Normalize;
const vch = q.GetEncoded;
const yu = curve.curve.DecodePoint(vch);
const domain = TECDomainParameters.Create(curve.curve, curve.G, curve.n, curve.H, curve.GetSeed);
const pubKey: IECPublicKeyParameters = TECPublicKeyParameters.Create('EC', yu, domain);
Result := TResult<TAddress>.Ok(publicKeyToAddress(pubKey));
end;
{ TEthereumSigner }
constructor TEthereumSigner.Create;
begin
inherited Create(THMacDsaKCalculator.Create(TDigestUtilities.GetDigest('SHA-256')));
end;
function TEthereumSigner.GenerateSignature(const msg: TCryptoLibByteArray): TECDsaSignature;
begin
Result := inherited GenerateSignature(SECP256K1, msg);
end;
{ TSignature }
constructor TSignature.Create(const R, S, V: TBigInteger);
begin
Self.R := R;
Self.S := S;
Self.V := V;
end;
class function TSignature.FromHex(const hex: string): IResult<TSignature>;
begin
const bytes = web3.utils.fromHex(hex);
if Length(bytes) < 65 then
begin
Result := TResult<TSignature>.Err('out of range');
EXIT;
end;
var output: TSignature;
output.R := TBigInteger.Create(1, copy(bytes, 0, 32));
output.S := TBigInteger.Create(1, copy(bytes, 32, 32));
output.V := TBigInteger.Create(1, copy(bytes, 64, 1));
Result := TResult<TSignature>.Ok(output);
end;
function TSignature.ToHex: string;
begin
var R := Self.R.ToByteArrayUnsigned;
while Length(R) < 32 do R := [0] + R;
var S := Self.S.ToByteArrayUnsigned;
while Length(S) < 32 do S := [0] + S;
var V := Self.V.ToByteArrayUnsigned;
if Length(V) < 1 then V := [0];
Result := web3.utils.toHex(R + S + V);
end;
end.