-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathDogeMessageLibrary.sol
1737 lines (1550 loc) · 57.4 KB
/
DogeMessageLibrary.sol
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// Bitcoin transaction parsing library - modified for DOGE
// Copyright 2016 rain <https://keybase.io/rain>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// https://en.bitcoin.it/wiki/Protocol_documentation#tx
//
// Raw Bitcoin transaction structure:
//
// field | size | type | description
// version | 4 | int32 | transaction version number
// n_tx_in | 1-9 | var_int | number of transaction inputs
// tx_in | 41+ | tx_in[] | list of transaction inputs
// n_tx_out | 1-9 | var_int | number of transaction outputs
// tx_out | 9+ | tx_out[] | list of transaction outputs
// lock_time | 4 | uint32 | block number / timestamp at which tx locked
//
// Transaction input (tx_in) structure:
//
// field | size | type | description
// previous | 36 | outpoint | Previous output transaction reference
// script_len | 1-9 | var_int | Length of the signature script
// sig_script | ? | uchar[] | Script for confirming transaction authorization
// sequence | 4 | uint32 | Sender transaction version
//
// OutPoint structure:
//
// field | size | type | description
// hash | 32 | char[32] | The hash of the referenced transaction
// index | 4 | uint32 | The index of this output in the referenced transaction
//
// Transaction output (tx_out) structure:
//
// field | size | type | description
// value | 8 | int64 | Transaction value (Satoshis)
// pk_script_len | 1-9 | var_int | Length of the public key script
// pk_script | ? | uchar[] | Public key as a Bitcoin script.
//
// Variable integers (var_int) can be encoded differently depending
// on the represented value, to save space. Variable integers always
// precede an array of a variable length data type (e.g. tx_in).
//
// Variable integer encodings as a function of represented value:
//
// value | bytes | format
// <0xFD (253) | 1 | uint8
// <=0xFFFF (65535)| 3 | 0xFD followed by length as uint16
// <=0xFFFF FFFF | 5 | 0xFE followed by length as uint32
// - | 9 | 0xFF followed by length as uint64
//
// Public key scripts `pk_script` are set on the output and can
// take a number of forms. The regular transaction script is
// called 'pay-to-pubkey-hash' (P2PKH):
//
// OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
//
// OP_x are Bitcoin script opcodes. The bytes representation (including
// the 0x14 20-byte stack push) is:
//
// 0x76 0xA9 0x14 <pubKeyHash> 0x88 0xAC
//
// The <pubKeyHash> is the ripemd160 hash of the sha256 hash of
// the public key, preceded by a network version byte. (21 bytes total)
//
// Network version bytes: 0x00 (mainnet); 0x6f (testnet); 0x34 (namecoin)
//
// The Bitcoin address is derived from the pubKeyHash. The binary form is the
// pubKeyHash, plus a checksum at the end. The checksum is the first 4 bytes
// of the (32 byte) double sha256 of the pubKeyHash. (25 bytes total)
// This is converted to base58 to form the publicly used Bitcoin address.
// Mainnet P2PKH transaction scripts are to addresses beginning with '1'.
//
// P2SH ('pay to script hash') scripts only supply a script hash. The spender
// must then provide the script that would allow them to redeem this output.
// This allows for arbitrarily complex scripts to be funded using only a
// hash of the script, and moves the onus on providing the script from
// the spender to the redeemer.
//
// The P2SH script format is simple:
//
// OP_HASH160 <scriptHash> OP_EQUAL
//
// 0xA9 0x14 <scriptHash> 0x87
//
// The <scriptHash> is the ripemd160 hash of the sha256 hash of the
// redeem script. The P2SH address is derived from the scriptHash.
// Addresses are the scriptHash with a version prefix of 5, encoded as
// Base58check. These addresses begin with a '3'.
pragma solidity ^0.7.6;
// parse a raw Dogecoin transaction byte array
library DogeMessageLibrary {
uint256 constant p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f; // secp256k1
uint256 constant q = (p + 1) / 4;
// Offset for the transaction inputs.
// This offset is constant because the version field is of fixed size.
uint256 constant TX_INPUTS_OFFSET = 4;
// Error codes
uint256 constant ERR_INVALID_HEADER = 10050;
uint256 constant ERR_COINBASE_INDEX = 10060; // coinbase tx index within Litecoin merkle isn't 0
uint256 constant ERR_NOT_MERGE_MINED = 10070; // trying to check AuxPoW on a block that wasn't merge mined
uint256 constant ERR_FOUND_TWICE = 10080; // 0xfabe6d6d found twice
uint256 constant ERR_NO_MERGE_HEADER = 10090; // 0xfabe6d6d not found
uint256 constant ERR_NOT_IN_FIRST_20 = 10100; // chain Merkle root isn't in the first 20 bytes of coinbase tx
uint256 constant ERR_CHAIN_MERKLE = 10110;
uint256 constant ERR_PARENT_MERKLE = 10120;
uint256 constant ERR_PROOF_OF_WORK = 10130;
enum Network {
MAINNET,
TESTNET,
REGTEST
}
// AuxPoW block fields
struct AuxPoW {
uint256 scryptHash;
uint256 txHash;
uint256 coinbaseMerkleRoot; // Merkle root of auxiliary block hash tree; stored in coinbase tx field
uint256[] chainMerkleProof; // proves that a given Dogecoin block hash belongs to a tree with the above root
uint256 dogeHashIndex; // index of Doge block hash within block hash tree
uint256 coinbaseMerkleRootCode; // encodes whether or not the root was found properly
uint256 parentMerkleRoot; // Merkle root of transaction tree from parent Litecoin block header
uint256[] parentMerkleProof; // proves that coinbase tx belongs to a tree with the above root
uint256 coinbaseTxIndex; // index of coinbase tx within Litecoin tx tree
uint256 parentNonce;
}
// Dogecoin block header stored as a struct, mostly for readability purposes.
// BlockHeader structs can be obtained by parsing a block header's first 80 bytes
// with parseHeaderBytes.
struct BlockHeader {
uint32 version;
uint32 time;
uint32 bits;
uint32 nonce;
uint256 blockHash;
uint256 prevBlock;
uint256 merkleRoot;
}
// Describes the input and where its script can be found.
struct InputDescriptor {
// Byte offset where the input is located in the tx
uint256 offset;
// Byte offset where the signature script is located in the tx
uint256 sigScriptOffset;
// Length of the signature script
uint256 sigScriptLength;
}
// Outpoints are references to a particular output in a tx.
// At the time a transaction is built, an outpoint should
// derreference to an unspent transaction output.
struct Outpoint {
// Tx id
uint256 txHash;
// Index of output consumed in tx
uint32 txIndex;
}
struct P2PKHOutput {
uint64 value;
bytes20 publicKeyHash;
}
/**
* Convert a variable integer into a Solidity numeric type.
*
* @return the integer as a uint256
* @return the byte index after the var integer
*/
function parseVarInt(bytes memory txBytes, uint256 pos) private pure returns (uint256, uint256) {
// the first byte tells us how big the integer is
uint8 ibit = uint8(txBytes[pos]);
pos += 1; // skip ibit
if (ibit < 0xfd) {
return (ibit, pos);
} else if (ibit == 0xfd) {
return (readUint16LE(txBytes, pos), pos + 2);
} else if (ibit == 0xfe) {
return (readUint32LE(txBytes, pos), pos + 4);
}
/*if (ibit == 0xff)*/
else {
return (readUint64LE(txBytes, pos), pos + 8);
}
}
// Read a uint16 value from buffer in little endian format.
function readUint16LE(bytes memory data, uint256 pos) private pure returns (uint16) {
return uint16(uint8(data[pos])) + (uint16(uint8(data[pos + 1])) << 8);
}
// Read a uint32 value from buffer in little endian format.
function readUint32LE(bytes memory data, uint256 pos) private pure returns (uint32) {
return
uint32(uint8(data[pos])) +
(uint32(uint8(data[pos + 1])) << 8) +
(uint32(uint8(data[pos + 2])) << 16) +
(uint32(uint8(data[pos + 3])) << 24);
}
// Read a uint64 value from buffer in little endian format.
function readUint64LE(bytes memory data, uint256 pos) private pure returns (uint64) {
return
uint64(uint8(data[pos])) +
(uint64(uint8(data[pos + 1])) << 8) +
(uint64(uint8(data[pos + 2])) << 16) +
(uint64(uint8(data[pos + 3])) << 24) +
(uint64(uint8(data[pos + 4])) << 32) +
(uint64(uint8(data[pos + 5])) << 40) +
(uint64(uint8(data[pos + 6])) << 48) +
(uint64(uint8(data[pos + 7])) << 56);
}
// Read uint256 value from buffer in little endian format.
function readUint256LE(bytes memory data, uint256 start) private pure returns (uint256 res) {
require(start + 31 < data.length, "Invalid uint256 LE read from buffer");
for (uint256 i = 0; i < 32; i++) {
res += uint256(uint8(data[i + start])) << (8 * i);
}
}
// Read uint256 value from buffer in big endian format.
function readUint256BE(bytes memory data, uint256 start) private pure returns (uint256 res) {
require(start + 31 < data.length, "Invalid uint256 BE read from buffer");
for (uint256 i = 0; i < 32; i++) {
res += uint256(uint8(data[i + start])) << (8 * (31 - i));
}
}
/**
* @dev - Parses a specific input in a tx to return its outpoint, i.e., its tx output reference.
* @param txBytes - tx byte array
* @param txInputIndex - Output index in tx.
* @return spentTxHash Tx hash of the outpoint.
* @return spentTxIndex Tx index of the outpoint.
*/
function getInputOutpoint(bytes memory txBytes, uint32 txInputIndex)
internal
pure
returns (uint256 spentTxHash, uint32 spentTxIndex)
{
uint256 pos = TX_INPUTS_OFFSET;
(
spentTxHash,
spentTxIndex, /*pos*/
) = getOutpointFromInputsByIndex(txBytes, pos, txInputIndex);
}
/**
* @dev - Parses an unlock doge tx
* Inputs
* One or more inputs signed by the operator.
* The rest of the inputs are ignored.
*
* Ouputs
* 0. Output for the user. Must contain a P2PKH script.
* 1. Optional. Operator change. Must contain a P2PKH script.
* The rest of the outputs are ignored
* If there is no change for the operator, the second output is ignored.
*
* @param txBytes - tx byte array
* @param amountOfInputs - Amount of inputs expected to be parsed.
* @param amountOfOutputs - Amount of outputs expected to be parsed.
* All parsed outputs must contain P2PKH scripts.
* @return outpoints References to previous tx outputs that are consumed in this tx.
* @return outputs P2PKH outputs parsed in the transaction.
*/
function parseUnlockTransaction(
bytes memory txBytes,
uint256 amountOfInputs,
uint256 amountOfOutputs
) internal pure returns (Outpoint[] memory outpoints, P2PKHOutput[] memory outputs) {
uint256 pos = TX_INPUTS_OFFSET;
(outpoints, pos) = getUnlockInputs(txBytes, pos, amountOfInputs);
outputs = parseUnlockTxOutputs(txBytes, pos, amountOfOutputs);
return (outpoints, outputs);
}
function getUnlockInputs(
bytes memory txBytes,
uint256 pos,
uint256 amountOfInputs
) private pure returns (Outpoint[] memory, uint256) {
InputDescriptor[] memory inputScripts;
(inputScripts, pos) = scanInputs(txBytes, pos, amountOfInputs);
Outpoint[] memory outpoints = new Outpoint[](inputScripts.length);
for (uint256 i = 0; i < inputScripts.length; i++) {
// We need to flip the tx hash bytes to have it in reversed byte order as specified in the protocol.
// We could use internal byte order and flip the hash later on when necessary but
// that would add complexity to the usage of these functions.
// See https://github.com/bitcoin-dot-org/bitcoin.org/issues/580
// Interpreting this value as a little endian uint256 lets us reverse it as soon as we read it.
uint256 inputOffset = inputScripts[i].offset;
outpoints[i].txHash = readUint256LE(txBytes, inputOffset);
outpoints[i].txIndex = readUint32LE(txBytes, inputOffset + 32);
}
return (outpoints, pos);
}
/**
* Determine the operator output, if any, and the value of the user output
* Ouputs
* 0. Output for the user. Must contain a P2PKH script.
* 1. Optional. Operator change. Must contain a P2PKH script.
* The rest of the outputs are ignored
* If there is no change for the operator, the second output is ignored.
*
* @param txBytes - tx byte array
* @param pos - position to start parsing txBytes
* @param amountOfOutputs - Amount of outputs expected to be parsed.
* All parsed outputs must contain P2PKH scripts.
* @return outputs P2PKH outputs parsed in the transaction.
*
* Returns output amount, index and ethereum address
*/
function parseUnlockTxOutputs(
bytes memory txBytes,
uint256 pos,
uint256 amountOfOutputs
) private pure returns (P2PKHOutput[] memory) {
uint256 nOutputs;
(nOutputs, pos) = parseVarInt(txBytes, pos);
require(amountOfOutputs <= nOutputs, "The unlock transaction doesn't have enough outputs.");
P2PKHOutput[] memory outputs = new P2PKHOutput[](amountOfOutputs);
for (uint256 i = 0; i < outputs.length; i++) {
bytes20 userPublicKeyHash;
uint64 userValue;
(userPublicKeyHash, userValue, pos) = scanUnlockOutput(txBytes, pos);
outputs[i].value = userValue;
outputs[i].publicKeyHash = userPublicKeyHash;
}
return outputs;
}
// Scans a single output of an unlock transaction.
// The output script should be a P2PKH script.
// If this is not the case, the parsing fails with a revert.
// Returns the value, offset and length of scripts of the output.
function scanUnlockOutput(bytes memory txBytes, uint256 pos)
private
pure
returns (
bytes20,
uint64,
uint256
)
{
uint64 outputValue = readUint64LE(txBytes, pos);
pos += 8;
uint256 outputScriptLength;
(outputScriptLength, pos) = parseVarInt(txBytes, pos);
uint256 outputScriptStart = pos;
pos += outputScriptLength;
bytes20 outputPublicKeyHash = parseP2PKHOutputScript(
txBytes,
outputScriptStart,
outputScriptLength
);
return (outputPublicKeyHash, outputValue, pos);
}
// @dev - Parses a doge tx assuming it is a lock operation
//
// @param txBytes - tx byte array
// @param expectedOperatorPKH - public key hash that is expected to be used as output or input
// Outputs
// @return outputValue - amount sent to the lock address in satoshis
// @return lockDestinationEthAddress - address where tokens should be minted to
// @return outputIndex - number of output where expectedOperatorPKH was found
function parseLockTransaction(bytes memory txBytes, bytes20 expectedOperatorPKH)
internal
pure
returns (
uint256,
address,
uint32
)
{
uint256 pos = TX_INPUTS_OFFSET;
// Ignore inputs
pos = skipInputs(txBytes, pos);
address lockDestinationEthAddress;
uint256 operatorTxOutputValue;
(operatorTxOutputValue, lockDestinationEthAddress) = parseLockTxOutputs(
expectedOperatorPKH,
txBytes,
pos
);
require(lockDestinationEthAddress != address(0x0));
return (operatorTxOutputValue, lockDestinationEthAddress, 0);
}
/**
* Parse operator output and embedded ethereum address in transaction outputs in tx
*
* @param expectedOperatorPKH - operator public key hash to look for
* @param txBytes - tx byte array
* @param pos - position to start parsing txBytes
* Outputs
* @return output value of operator output
* @return lockDestinationEthAddress - Lock destination address if operator output and OP_RETURN output found, 0 otherwise
*
* Returns output amount, index and ethereum address
*/
function parseLockTxOutputs(
bytes20 expectedOperatorPKH,
bytes memory txBytes,
uint256 pos
) private pure returns (uint256, address) {
/*
Outputs
0. Operator
1. OP_RETURN with the ethereum address of the user
2. Optional. Change output for the user. This output is ignored.
*/
uint256 operatorOutputValue;
uint256 operatorScriptStart;
uint256 operatorScriptLength;
uint256 ethAddressScriptStart;
uint256 ethAddressScriptLength;
(
operatorOutputValue,
operatorScriptStart,
operatorScriptLength,
ethAddressScriptStart,
ethAddressScriptLength
) = scanLockOutputs(txBytes, pos);
// Check tx is sending funds to an operator.
bytes20 outputPublicKeyHash = parseP2PKHOutputScript(
txBytes,
operatorScriptStart,
operatorScriptLength
);
require(
outputPublicKeyHash == expectedOperatorPKH,
"The first tx output does not have a P2PKH output script for an operator."
);
// Read the destination Ethereum address
require(
isEthereumAddress(txBytes, ethAddressScriptStart, ethAddressScriptLength),
"The second tx output does not describe an ethereum address."
);
address lockDestinationEthAddress = readEthereumAddress(
txBytes,
ethAddressScriptStart,
ethAddressScriptLength
);
return (operatorOutputValue, lockDestinationEthAddress);
}
// Scan the outputs of a lock transaction.
// The first output in a lock transaction transfers value to an operator.
// The second output in a lock transaction is an unspendable output with an ethereum address.
// Returns the offsets and lengths of scripts for the first and second outputs and
// the value of the first output.
function scanLockOutputs(bytes memory txBytes, uint256 pos)
private
pure
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
uint256 nOutputs;
(nOutputs, pos) = parseVarInt(txBytes, pos);
require(nOutputs == 2 || nOutputs == 3, "Lock transactions only have two or three outputs.");
// Tx output 0 is for the operator
// read value of the output for the operator
uint256 operatorOutputValue = readUint64LE(txBytes, pos);
pos += 8;
// read the script length
uint256 operatorScriptLength;
(operatorScriptLength, pos) = parseVarInt(txBytes, pos);
uint256 operatorScriptStart = pos;
pos += operatorScriptLength;
// Tx output 1 describes the ethereum address that should receive the dogecoin tokens
// skip value
pos += 8;
uint256 ethAddressScriptLength;
uint256 ethAddressScriptStart;
(ethAddressScriptLength, ethAddressScriptStart) = parseVarInt(txBytes, pos);
return (
operatorOutputValue,
operatorScriptStart,
operatorScriptLength,
ethAddressScriptStart,
ethAddressScriptLength
);
}
/**
* Scan some inputs and find their script lengths.
* The rest of the inputs are consumed but ignored otherwise.
* @param desiredInputs Number of outputs to scan through. desiredInputs=0 => scan all.
* If the amount of inputs is less than the desired inputs, the scan reverts the transaction.
* @return Array of input descriptors.
* @return The position where the outputs begin in the transaction.
*/
function scanInputs(
bytes memory txBytes,
uint256 pos,
uint256 desiredInputs
) private pure returns (InputDescriptor[] memory, uint256) {
uint256 nInputs;
uint256 halt;
(nInputs, pos) = parseVarInt(txBytes, pos);
require(desiredInputs <= nInputs, "The transaction doesn't have enough inputs.");
if (desiredInputs == 0) {
halt = nInputs;
} else {
halt = desiredInputs;
}
InputDescriptor[] memory inputs = new InputDescriptor[](halt);
uint256 i;
for (i = 0; i < halt; i++) {
inputs[i].offset = pos;
// skip outpoint
pos += 36;
uint256 scriptLength;
(scriptLength, pos) = parseVarInt(txBytes, pos);
inputs[i].sigScriptOffset = pos;
inputs[i].sigScriptLength = scriptLength;
// skip sig_script, seq
pos += scriptLength + 4;
}
// Skip the rest of the inputs to consume them and obtain outputs offset.
for (; i < nInputs; i++) {
// skip outpoint
pos += 36;
uint256 scriptLength;
(scriptLength, pos) = parseVarInt(txBytes, pos);
// skip sig_script and seq
pos += scriptLength + 4;
}
return (inputs, pos);
}
/**
* Returns the nth input outpoint. Outpoints are the tx hash and output index within the tx.
* Reverts if the index is out of bounds for the input array.
* @return dogeTxHash Tx hash referenced in input.
* @return dogeTxIndex Output index within referenced tx.
*/
function getOutpointFromInputsByIndex(
bytes memory txBytes,
uint256 pos,
uint256 index
)
private
pure
returns (
uint256 dogeTxHash,
uint32 dogeTxIndex,
uint256
)
{
uint256 n_inputs;
(n_inputs, pos) = parseVarInt(txBytes, pos);
require(index < n_inputs, "Requested index is out of bounds for input array in tx.");
for (uint256 i = 0; i < index; i++) {
// skip outpoint
pos += 36;
uint256 script_len;
(script_len, pos) = parseVarInt(txBytes, pos);
// skip sig_script and seq
pos += script_len + 4;
}
// We need to flip the tx hash bytes to have it in reversed byte order as specified in the protocol.
// We could use internal byte order and flip the hash later on when necessary but
// that would add complexity to the usage of these functions.
// See https://github.com/bitcoin-dot-org/bitcoin.org/issues/580
// Interpreting this value as a little endian uint256 lets us reverse it as soon as we read it.
uint256 txHash = readUint256LE(txBytes, pos);
pos += 32;
uint32 txIndex = readUint32LE(txBytes, pos);
pos += 4;
return (txHash, txIndex, pos);
}
/**
* Consumes all inputs in a transaction without storing anything in memory
* @return index to tx output quantity var integer
*/
function skipInputs(bytes memory txBytes, uint256 pos) private pure returns (uint256) {
uint256 n_inputs;
(n_inputs, pos) = parseVarInt(txBytes, pos);
for (uint256 i = 0; i < n_inputs; i++) {
// skip outpoint
pos += 36;
uint256 script_len;
(script_len, pos) = parseVarInt(txBytes, pos);
// skip sig_script and seq
pos += script_len + 4;
}
return pos;
}
// similar to scanInputs, but consumes less gas since it doesn't store the inputs
// also returns position of coinbase tx for later use
function skipInputsAndGetScriptPos(
bytes memory txBytes,
uint256 pos,
uint256 stop
) private pure returns (uint256, uint256) {
uint256 script_pos;
uint256 n_inputs;
uint256 halt;
uint256 script_len;
(n_inputs, pos) = parseVarInt(txBytes, pos);
if (stop == 0 || stop > n_inputs) {
halt = n_inputs;
} else {
halt = stop;
}
for (uint256 i = 0; i < halt; i++) {
pos += 36; // skip outpoint
(script_len, pos) = parseVarInt(txBytes, pos);
if (i == 0) script_pos = pos; // first input script begins where first script length ends
// (script_len, pos) = (1, 0);
pos += script_len + 4; // skip sig_script, seq
}
return (pos, script_pos);
}
// scan the outputs and find the values and script lengths.
// return array of values, array of script lengths and the
// end position of the outputs.
// takes a 'stop' argument which sets the maximum number of
// outputs to scan through. stop=0 => scan all.
function scanOutputs(
bytes memory txBytes,
uint256 pos,
uint256 stop
)
private
pure
returns (
uint256[] memory,
uint256[] memory,
uint256[] memory,
uint256
)
{
uint256 n_outputs;
uint256 halt;
uint256 script_len;
(n_outputs, pos) = parseVarInt(txBytes, pos);
if (stop == 0 || stop > n_outputs) {
halt = n_outputs;
} else {
halt = stop;
}
uint256[] memory script_starts = new uint256[](halt);
uint256[] memory script_lens = new uint256[](halt);
uint256[] memory output_values = new uint256[](halt);
for (uint256 i = 0; i < halt; i++) {
output_values[i] = readUint64LE(txBytes, pos);
pos += 8;
(script_len, pos) = parseVarInt(txBytes, pos);
script_starts[i] = pos;
script_lens[i] = script_len;
pos += script_len;
}
return (output_values, script_starts, script_lens, pos);
}
// similar to scanOutputs, but consumes less gas since it doesn't store the outputs
function skipOutputs(
bytes memory txBytes,
uint256 pos,
uint256 stop
) private pure returns (uint256) {
uint256 n_outputs;
uint256 halt;
uint256 script_len;
(n_outputs, pos) = parseVarInt(txBytes, pos);
if (stop == 0 || stop > n_outputs) {
halt = n_outputs;
} else {
halt = stop;
}
for (uint256 i = 0; i < halt; i++) {
pos += 8;
(script_len, pos) = parseVarInt(txBytes, pos);
pos += script_len;
}
return pos;
}
// get final position of inputs, outputs and lock time
// this is a helper function to slice a byte array and hash the inputs, outputs and lock time
function getSlicePosAndScriptPos(bytes memory txBytes, uint256 pos)
private
pure
returns (uint256 slicePos, uint256 scriptPos)
{
(slicePos, scriptPos) = skipInputsAndGetScriptPos(txBytes, pos + 4, 0);
slicePos = skipOutputs(txBytes, slicePos, 0);
slicePos += 4; // skip lock time
}
// scan a Merkle branch.
// return array of values and the end position of the sibling hashes.
// takes a 'stop' argument which sets the maximum number of
// siblings to scan through. stop=0 => scan all.
function scanMerkleBranch(
bytes memory txBytes,
uint256 pos,
uint256 stop
) private pure returns (uint256[] memory, uint256) {
uint256 n_siblings;
uint256 halt;
(n_siblings, pos) = parseVarInt(txBytes, pos);
if (stop == 0 || stop > n_siblings) {
halt = n_siblings;
} else {
halt = stop;
}
uint256[] memory sibling_values = new uint256[](halt);
for (uint256 i = 0; i < halt; i++) {
sibling_values[i] = flip32Bytes(readUint256BE(txBytes, pos));
pos += 32;
}
return (sibling_values, pos);
}
// Slice 20 contiguous bytes from bytes `data`, starting at `start`
function sliceBytes20(bytes memory data, uint256 start) private pure returns (bytes20) {
uint160 slice = 0;
// FIXME: With solc v0.4.24 and optimizations enabled
// using uint160 for index i will generate an error
// "Error: VM Exception while processing transaction: Error: redPow(normalNum)"
for (uint256 i = 0; i < 20; i++) {
slice += uint160(uint8(data[i + start])) << uint160(8 * (19 - i));
}
return bytes20(slice);
}
// @dev returns a portion of a given byte array specified by its starting and ending points
// Should be private, made internal for testing
//
// @param rawBytes - array to be sliced
// @param offset - first byte of sliced array
// @param endIndex - last byte of sliced array
function sliceArray(
bytes memory rawBytes,
uint256 offset,
uint256 endIndex
) internal view returns (bytes memory) {
uint256 len = endIndex - offset;
bytes memory result = new bytes(len);
assembly {
// Call precompiled contract to copy data
if iszero(
staticcall(gas(), 0x04, add(add(rawBytes, 0x20), offset), len, add(result, 0x20), len)
) {
revert(0, 0)
}
}
return result;
}
// returns true if the bytes located in txBytes by pos and
// script_len represent a P2PKH script
function isP2PKH(
bytes memory txBytes,
uint256 pos,
uint256 script_len
) private pure returns (bool) {
return
(script_len == 25) && // 20 byte pubkeyhash + 5 bytes of script
(txBytes[pos] == 0x76) && // OP_DUP
(txBytes[pos + 1] == 0xa9) && // OP_HASH160
(uint8(txBytes[pos + 2]) == 20) && // bytes to push
(txBytes[pos + 23] == 0x88) && // OP_EQUALVERIFY
(txBytes[pos + 24] == 0xac); // OP_CHECKSIG
}
// Get the pubkeyhash from an output script. Assumes
// pay-to-pubkey-hash (P2PKH) outputs.
// Returns the pubkeyhash, or zero if unknown output.
function parseP2PKHOutputScript(
bytes memory txBytes,
uint256 pos,
uint256 script_len
) private pure returns (bytes20) {
require(isP2PKH(txBytes, pos, script_len), "Expected a P2PKH script in output.");
return sliceBytes20(txBytes, pos + 3);
}
// Extract a signature
function parseSignature(bytes memory txBytes, uint256 pos)
private
pure
returns (bytes memory, uint256)
{
uint8 op;
bytes memory sig;
(op, pos) = getOpcode(txBytes, pos);
require(op >= 9 && op <= 73);
require(uint8(txBytes[pos]) == 0x30);
//FIXME: Copy signature
pos += op;
return (sig, pos);
}
// Extract public key
function parsePubKey(bytes memory txBytes, uint256 pos)
private
pure
returns (
bytes32,
bool,
uint256
)
{
uint8 op;
(op, pos) = getOpcode(txBytes, pos);
//FIXME: Add support for uncompressed public keys
require(op == 33, "Expected a compressed public key");
bytes32 pubKey;
bool odd = txBytes[pos] == 0x03;
pos += 1;
assembly {
pubKey := mload(add(add(txBytes, 0x20), pos))
}
pos += 32;
return (pubKey, odd, pos);
}
/**
* Returns true if the tx output is an embedded ethereum address
* @param txBytes Buffer where the entire transaction is stored.
* @param pos Index into the tx buffer where the script is stored.
* @param len Size of the script in terms of bytes.
*/
function isEthereumAddress(
bytes memory txBytes,
uint256 pos,
uint256 len
) private pure returns (bool) {
// scriptPub format for the ethereum address is
// 0x6a OP_RETURN
// 0x14 PUSH20
// [] 20 bytes of the ethereum address
return len == 20 + 2 && txBytes[pos] == bytes1(0x6a) && txBytes[pos + 1] == bytes1(0x14);
}
// Read the ethereum address embedded in the tx output
function readEthereumAddress(
bytes memory txBytes,
uint256 pos,
uint256
) private pure returns (address) {
uint256 data;
assembly {
data := mload(add(add(txBytes, 22), pos))
}
return address(uint160(data));
}
// Read next opcode from script
function getOpcode(bytes memory txBytes, uint256 pos) private pure returns (uint8, uint256) {
return (uint8(txBytes[pos]), pos + 1);
}
function expmod(
uint256 base,
uint256 e,
uint256 m
) internal view returns (uint256 o) {
assembly {
// pointer to free memory
let pos := mload(0x40)
mstore(pos, 0x20) // Length of Base
mstore(add(pos, 0x20), 0x20) // Length of Exponent
mstore(add(pos, 0x40), 0x20) // Length of Modulus
mstore(add(pos, 0x60), base) // Base
mstore(add(pos, 0x80), e) // Exponent
mstore(add(pos, 0xa0), m) // Modulus
// call modexp precompile!
if iszero(staticcall(gas(), 0x05, pos, 0xc0, pos, 0x20)) {
revert(0, 0)
}
// data
o := mload(pos)
}
}
function pub2address(uint256 x, bool odd) internal view returns (address) {
// First, uncompress pub key
uint256 yy = mulmod(x, x, p);
yy = mulmod(yy, x, p);
yy = addmod(yy, 7, p);
uint256 y = expmod(yy, q, p);
if (((y & 1) == 1) != odd) {
y = p - y;
}
require(yy == mulmod(y, y, p));
// Now, with uncompressed x and y, create the address
return address(uint160(uint256(keccak256(abi.encodePacked(x, y)))));
}
// Gets the public key hash given a public key
function pub2PubKeyHash(bytes32 pub, bool odd) internal pure returns (bytes20) {
bytes1 firstByte = odd ? bytes1(0x03) : bytes1(0x02);
return ripemd160(abi.encodePacked(sha256(abi.encodePacked(firstByte, pub))));
}
/**