-
Notifications
You must be signed in to change notification settings - Fork 22
/
Wallet.class.php
325 lines (275 loc) · 9.21 KB
/
Wallet.class.php
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
<?php
/*
* Crypto Currency Wallet
* For Bitcoin/Zetacoin compatable Crypto Currency utilizing the secp256k1 curve
* @author Daniel Morante
* Some parts may contain work based on Jan Moritz Lindemann, Matyas Danter, and Joey Hewitt
*/
class Wallet{
private $PRIVATE_KEY;
private $MESSAGE_MAGIC;
private $NETWORK_PREFIX;
private $NETWORK_NAME;
public function __construct(PrivateKey $private_key = null, $networkPrefix = '00', $networkName = 'Bitcoin', $messageMagic = null){
// Private key
if(!empty($private_key)){
$this->PRIVATE_KEY = $private_key;
}
// The prefix, network name, and message magic
$this->setNetworkPrefix($networkPrefix);
$this->setNetworkName($networkName);
$this->setMessageMagic($messageMagic);
}
/***
* Set the network prefix, '00' = main network, '6f' = test network.
*
* @param String Hex $prefix
*/
public function setNetworkPrefix($prefix){
// The prefix
if(!empty($prefix)){
$this->NETWORK_PREFIX = $prefix;
}
}
/**
* Returns the current network prefix, '00' = main network, '6f' = test network.
*
* @return String Hex
*/
public function getNetworkPrefix(){
return $this->NETWORK_PREFIX;
}
/***
* Set the network name
*
* @param String $name
*/
public function setNetworkName($name){
// The network name
if(!empty($name)){
$this->NETWORK_NAME = $name;
}
}
/**
* Returns the current network name
*
* @return String
*/
public function getNetworkName(){
return $this->NETWORK_NAME;
}
/***
* Set the magic message prefix
*
* @param String $magic
*/
public function setMessageMagic($magic){
// The signed message "magic" prefix.
$this->MESSAGE_MAGIC = $magic;
}
/**
* Returns the current magic message prefix
*
* @return String
*/
public function getMessageMagic(){
// Check if a custom messageMagic is being used
if(!empty($this->MESSAGE_MAGIC)){
// Use the custom one.
$magic = $this->MESSAGE_MAGIC;
}
else{
// Use the default which is: "[LINE_LEN] [NETWORK_NAME] Signed Message:\n"
$default = $this->getNetworkName() . " Signed Message:\n";
$magic = $this->numToVarIntString(strlen($default)) . $default;
}
return $magic;
}
/***
* returns the compressed Bitcoin address generated from the private key.
*
* @param string $derPubKey
* @return String Base58
*/
public function getAddress(){
$PubKeyPoints = $this->getPrivateKey()->getPubKeyPoints();
$DERPubkey = AddressCodec::Compress($PubKeyPoints);
return AddressCodec::Encode(AddressCodec::Hash($DERPubkey), $this->getNetworkPrefix());
}
public function getUncompressedAddress(){
$PubKeyPoints = $this->getPrivateKey()->getPubKeyPoints();
return AddressCodec::Hex(AddressCodec::Hash($PubKeyPoints));
}
private function getPrivateKey(){
if(empty($this->PRIVATE_KEY)){
throw new \Exception('Wallet does not have a private key');
}
else{
return $this->PRIVATE_KEY;
}
}
/***
* Satoshi client's standard message signature implementation.
*
* @param $message
* @param bool $compressed
* @param null $nonce
* @return string
* @throws \Exception
*/
public function signMessage($message, $compressed = true, $nonce = null)
{
$hash = $this->hash256($this->getMessageMagic() . $this->numToVarIntString(strlen($message)). $message);
$points = Signature::getSignatureHashPoints(
$hash,
$this->getPrivateKey()->getPrivateKey(),
$nonce
);
$R = $points['R'];
$S = $points['S'];
while(strlen($R) < 64)
$R = '0' . $R;
while(strlen($S) < 64)
$S = '0' . $S;
$res = "\n-----BEGIN " . strtoupper($this->getNetworkName()) . " SIGNED MESSAGE-----\n";
$res .= $message;
$res .= "\n-----BEGIN SIGNATURE-----\n";
if(true == $compressed)
$res .= $this->getAddress() . "\n";
else
$res .= $this->getUncompressedAddress() . "\n";
$finalFlag = 0;
for($i = 0; $i < 4; $i++)
{
$flag = 27;
if(true == $compressed)
$flag += 4;
$flag += $i;
$pubKeyPts =$this->getPrivateKey()->getPubKeyPoints();
//echo "\nReal pubKey : \n";
//print_r($pubKeyPts);
$recoveredPubKey = Signature::getPubKeyWithRS($flag, $R, $S, $hash);
//echo "\nRecovered PubKey : \n";
//print_r($recoveredPubKey);
if(AddressCodec::Compress($pubKeyPts) == $recoveredPubKey)
{
$finalFlag = $flag;
}
}
//echo "Final flag : " . dechex($finalFlag) . "\n";
if(0 == $finalFlag)
{
throw new \Exception('Unable to get a valid signature flag.');
}
$res .= base64_encode(hex2bin(dechex($finalFlag) . $R . $S));
$res .= "\n-----END " . strtoupper($this->getNetworkName()) . " SIGNED MESSAGE-----";
return $res;
}
/***
* checks the signature of a bitcoin signed message.
*
* @param $rawMessage
* @return bool
*/
public function checkSignatureForRawMessage($rawMessage)
{
//recover message.
preg_match_all("#-----BEGIN " . strtoupper($this->getNetworkName()) . " SIGNED MESSAGE-----\n(.{0,})\n-----BEGIN SIGNATURE-----\n#USi", $rawMessage, $out);
$message = $out[1][0];
preg_match_all("#\n-----BEGIN SIGNATURE-----\n(.{0,})\n(.{0,})\n-----END " . strtoupper($this->getNetworkName()) . " SIGNED MESSAGE-----#USi", $rawMessage, $out);
$address = $out[1][0];
$signature = $out[2][0];
// Alternate version
//return $this->checkSignedMessage($address, $signature, $message);
return $this->checkSignatureForMessage($address, $signature, $message);
}
/***
* checks the signature of a bitcoin signed message.
*
* @param $address String
* @param $encodedSignature String
* @param $message String
* @return bool
*/
public function checkSignatureForMessage($address, $encodedSignature, $message)
{
// $hash is HEX String
$hash = $this->hash256($this->getMessageMagic() . $this->numToVarIntString(strlen($message)) . $message);
//recover flag
// $signature is BIN
$signature = base64_decode($encodedSignature);
// $flag is INT
$flag = hexdec(bin2hex(substr($signature, 0, 1)));
// Convert BIN to HEX String
$R = bin2hex(substr($signature, 1, 32));
$S = bin2hex(substr($signature, 33));
$derPubKey = Signature::getPubKeyWithRS($flag, $R, $S, $hash);
$recoveredAddress = AddressCodec::Encode(AddressCodec::Hash($derPubKey), $this->getNetworkPrefix());
/* Alternate version
$pubkeyPoint = Signature::recoverPublicKey_HEX($flag, $R, $S, $hash);
$recoveredAddress = AddressCodec::Encode(AddressCodec::Hash(AddressCodec::Compress($pubkeyPoint)), $this->getNetworkPrefix());
*/
if($address == $recoveredAddress)
return true;
else
return false;
}
// Same as above - But not working correctly
// All Paramaters are Strings
public function checkSignedMessage($address, $encodedSignature, $message){
// $signature is BIN
$signature = base64_decode($encodedSignature, true);
// $recoveryFlags is INT
$recoveryFlags = ord($signature[0]) - 27;
if ($recoveryFlags < 0 || $recoveryFlags > 7) {
throw new InvalidArgumentException('invalid signature type');
}
// $isCompressed is BOOL
$isCompressed = ($recoveryFlags & 4) != 0;
// $hash is HEX String
$hash = $this->hash256($this->getMessageMagic() . $this->numToVarIntString(strlen($message)) . $message);
// Convert BIN to HEX String
$R = gmp_init(bin2hex(substr($signature, 1, 32)), 16);
$S = gmp_init(bin2hex(substr($signature, 33)), 16);
$hash = gmp_init($hash, 16);
// $pubkey is Array(HEX String, HEX String)
$pubkeyPoint = Signature::recoverPublicKey($R, $S, $hash, $recoveryFlags);
if ($isCompressed) {
$recoveredAddress = AddressCodec::Compress($pubkeyPoint);
}
else{
$recoveredAddress = AddressCodec::Hex($pubkeyPoint);
}
$recoveredAddress = AddressCodec::Encode(AddressCodec::Hash($recoveredAddress), $this->getNetworkPrefix());
return $address === $recoveredAddress;
}
/***
* Standard 256 bit hash function : double sha256
*
* @param $data
* @return string
*/
private function hash256($data){
return hash('sha256', hex2bin(hash('sha256', $data)));
}
/***
* Convert a number to a compact Int
* taken from https://github.com/scintill/php-bitcoin-signature-routines/blob/master/verifymessage.php
*
* @param $i
* @return string
* @throws \Exception
*/
private function numToVarIntString($i) {
if ($i < 0xfd) {
return chr($i);
} else if ($i <= 0xffff) {
return pack('Cv', 0xfd, $i);
} else if ($i <= 0xffffffff) {
return pack('CV', 0xfe, $i);
} else {
throw new \Exception('int too large');
}
}
}
?>