Repository navigation
Expand file tree
/
Copy pathprecompiles.rs
More file actions
3234 lines (2837 loc) · 126 KB
/
Copy pathprecompiles.rs
File metadata and controls
3234 lines (2837 loc) · 126 KB
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
/// RSK precompiled contracts for revm.
///
/// RSK extends Ethereum's standard precompiles (0x01–0x09) with its own
/// native contracts at higher addresses (0x01000006+). This module defines
/// all RSK precompile addresses, implements the RSK-specific ones, and
/// provides a builder that produces the complete `Precompiles` set for a
/// given block height.
///
/// ## Address Layout
///
/// | Range | Type | Examples |
/// |----------------|---------------------|---------------------------------|
/// | 0x01–0x05 | Ethereum (genesis) | ECRecover, SHA256, Identity |
/// | 0x06–0x08 | Ethereum (RSKIP137) | BN128 add/mul/pairing |
/// | 0x09 | Ethereum (RSKIP153) | Blake2F |
/// | 0x01000006 | RSK (genesis) | Bridge |
/// | 0x01000008 | RSK (genesis) | REMASC |
/// | 0x01000009+ | RSK (various) | HDWalletUtils, BlockHeader, etc |
use alloy_primitives::{Address, Bytes, U256};
use revm::context::{Cfg, LocalContextTr};
use revm::context_interface::{Block as BlockTr, ContextTr, JournalTr};
use revm::handler::PrecompileProvider;
use revm::interpreter::{CallInput, CallInputs, Gas, InstructionResult, InterpreterResult};
use revm::precompile::{
Precompile, PrecompileId, PrecompileOutput, PrecompileError, Precompiles,
PrecompileSpecId,
};
use revm::primitives::hardfork::SpecId;
use rustock_storage::BlockStore;
use std::sync::Arc;
use crate::bridge::constants::BridgeConstants;
use crate::hardfork::{RskHardforkConfig, RskNetworkUpgrade};
use crate::remasc::RemascConfig;
// ---------------------------------------------------------------------------
// RSK-specific precompile addresses
// ---------------------------------------------------------------------------
pub const BRIDGE_ADDR: Address =
Address::new(hex_addr("0000000000000000000000000000000001000006"));
pub const REMASC_ADDR: Address =
Address::new(hex_addr("0000000000000000000000000000000001000008"));
pub const HD_WALLET_UTILS_ADDR: Address =
Address::new(hex_addr("0000000000000000000000000000000001000009"));
pub const BLOCK_HEADER_ADDR: Address =
Address::new(hex_addr("0000000000000000000000000000000001000010"));
pub const ENVIRONMENT_ADDR: Address =
Address::new(hex_addr("0000000000000000000000000000000001000011"));
pub const SECP256K1_ADD_ADDR: Address =
Address::new(hex_addr("0000000000000000000000000000000001000016"));
pub const SECP256K1_MUL_ADDR: Address =
Address::new(hex_addr("0000000000000000000000000000000001000017"));
/// rskj `PrecompiledContracts.GENESIS_ADDRESSES`: precompiles that exist from
/// genesis. At the RSKIP126 activation block all of them are created (if
/// absent) and get the contract storage-prefix marker
/// (`BlockExecutor.maintainPrecompiledContractStorageRoots`).
pub const GENESIS_PRECOMPILES: [Address; 7] = [
Address::new(hex_addr("0000000000000000000000000000000000000001")), // ecrecover
Address::new(hex_addr("0000000000000000000000000000000000000002")), // sha256
Address::new(hex_addr("0000000000000000000000000000000000000003")), // ripemd160
Address::new(hex_addr("0000000000000000000000000000000000000004")), // identity
Address::new(hex_addr("0000000000000000000000000000000000000005")), // modexp
BRIDGE_ADDR,
REMASC_ADDR,
];
/// rskj `PrecompiledContracts.CONSENSUS_ENABLED_ADDRESSES`: precompiles
/// enabled by a network upgrade. At each one's activation block rskj
/// re-creates the account (resetting nonce/balance) and writes the marker.
pub const CONSENSUS_ENABLED_PRECOMPILES: [(Address, crate::hardfork::RskNetworkUpgrade); 9] = [
(HD_WALLET_UTILS_ADDR, crate::hardfork::RskNetworkUpgrade::Wasabi100), // RSKIP106
(BLOCK_HEADER_ADDR, crate::hardfork::RskNetworkUpgrade::Wasabi100), // RSKIP119
(Address::new(hex_addr("0000000000000000000000000000000000000006")), crate::hardfork::RskNetworkUpgrade::Papyrus200), // altBN128 add, RSKIP137
(Address::new(hex_addr("0000000000000000000000000000000000000007")), crate::hardfork::RskNetworkUpgrade::Papyrus200), // altBN128 mul, RSKIP137
(Address::new(hex_addr("0000000000000000000000000000000000000008")), crate::hardfork::RskNetworkUpgrade::Papyrus200), // altBN128 pairing, RSKIP137
(Address::new(hex_addr("0000000000000000000000000000000000000009")), crate::hardfork::RskNetworkUpgrade::Iris300), // blake2f, RSKIP153
(ENVIRONMENT_ADDR, crate::hardfork::RskNetworkUpgrade::Arrowhead600), // RSKIP203
(SECP256K1_ADD_ADDR, crate::hardfork::RskNetworkUpgrade::Reed800), // RSKIP516
(SECP256K1_MUL_ADDR, crate::hardfork::RskNetworkUpgrade::Reed800), // RSKIP516
];
/// Returns all RSK precompile addresses (including standard Ethereum ones).
pub fn all_rsk_precompile_addresses() -> Vec<Address> {
vec![
BRIDGE_ADDR,
REMASC_ADDR,
HD_WALLET_UTILS_ADDR,
BLOCK_HEADER_ADDR,
ENVIRONMENT_ADDR,
SECP256K1_ADD_ADDR,
SECP256K1_MUL_ADDR,
]
}
// ---------------------------------------------------------------------------
// RSK precompile implementations
// ---------------------------------------------------------------------------
/// REMASC: Reward Manager Smart Contract.
/// Called as the last transaction in every block to distribute miner fees.
/// Gas cost: 0 (free). Returns empty output on success.
fn remasc_run(_input: &[u8], _gas_limit: u64) -> Result<PrecompileOutput, PrecompileError> {
Ok(PrecompileOutput::new(0, Vec::new().into()))
}
/// Bridge: BTC–RSK two-way peg bridge.
/// Full implementation is complex (~60 methods). For now, returns empty output
/// and charges a minimal gas cost. Will be fully implemented in a later phase.
fn bridge_run(_input: &[u8], gas_limit: u64) -> Result<PrecompileOutput, PrecompileError> {
let gas_cost = 10_000u64;
if gas_limit < gas_cost {
return Err(PrecompileError::OutOfGas);
}
Ok(PrecompileOutput::new(gas_cost, Vec::new().into()))
}
/// HDWalletUtils: BIP32/Base58Check/multisig operations (0x01000009).
///
/// 4 methods dispatched by 4-byte ABI selector:
/// - toBase58Check(bytes,int256) → string
/// - deriveExtendedPublicKey(string,string) → string
/// - extractPublicKeyFromExtendedPublicKey(string) → bytes
/// - getMultisigScriptHash(int256,bytes[]) → bytes
fn hd_wallet_utils_run(input: &[u8], gas_limit: u64) -> Result<PrecompileOutput, PrecompileError> {
if input.len() < 4 {
return Err(PrecompileError::other("HDWalletUtils: input too short for selector"));
}
let selector = [input[0], input[1], input[2], input[3]];
let data = &input[4..];
if selector == selector_of("toBase58Check(bytes,int256)") {
run_to_base58check(data, gas_limit)
} else if selector == selector_of("deriveExtendedPublicKey(string,string)") {
run_derive_extended_public_key(data, gas_limit)
} else if selector == selector_of("extractPublicKeyFromExtendedPublicKey(string)") {
run_extract_pubkey(data, gas_limit)
} else if selector == selector_of("getMultisigScriptHash(int256,bytes[])") {
run_get_multisig_script_hash(data, gas_limit)
} else {
Err(PrecompileError::other("HDWalletUtils: unknown method selector"))
}
}
/// BlockHeaderContract: exposes block header fields to smart contracts.
/// Stub — returns empty with base gas cost.
fn block_header_run(input: &[u8], gas_limit: u64) -> Result<PrecompileOutput, PrecompileError> {
let gas_cost = 4_000u64 + 2 * input.len() as u64;
if gas_limit < gas_cost {
return Err(PrecompileError::OutOfGas);
}
Ok(PrecompileOutput::new(gas_cost, Vec::new().into()))
}
/// Environment: provides call stack depth.
/// Gas cost: 0.
fn environment_run(_input: &[u8], _gas_limit: u64) -> Result<PrecompileOutput, PrecompileError> {
Ok(PrecompileOutput::new(0, Vec::new().into()))
}
/// Secp256k1 point addition.
/// Input: up to 128 bytes = [x1(32) | y1(32) | x2(32) | y2(32)], big-endian.
/// Output: 64 bytes = [x(32) | y(32)].
/// (0,0) represents the point at infinity.
/// Gas cost: 150.
fn secp256k1_add_run(input: &[u8], gas_limit: u64) -> Result<PrecompileOutput, PrecompileError> {
let gas_cost = 150u64;
if gas_limit < gas_cost {
return Err(PrecompileError::OutOfGas);
}
let p1 = parse_secp256k1_point(input, 0)?;
let p2 = parse_secp256k1_point(input, 64)?;
let result = p1 + p2;
Ok(PrecompileOutput::new(gas_cost, encode_secp256k1_point(result).into()))
}
/// Secp256k1 scalar multiplication.
/// Input: up to 96 bytes = [x(32) | y(32) | scalar(32)], big-endian.
/// Output: 64 bytes = [x(32) | y(32)].
/// Gas cost: 3000.
fn secp256k1_mul_run(input: &[u8], gas_limit: u64) -> Result<PrecompileOutput, PrecompileError> {
let gas_cost = 3_000u64;
if gas_limit < gas_cost {
return Err(PrecompileError::OutOfGas);
}
let point = parse_secp256k1_point(input, 0)?;
let scalar = parse_word(input, 64);
let k = <k256::Scalar as k256::elliptic_curve::ops::Reduce<k256::U256>>::reduce(
k256::U256::from_be_slice(&scalar),
);
let result = point * k;
Ok(PrecompileOutput::new(gas_cost, encode_secp256k1_point(result).into()))
}
/// Read a 32-byte big-endian word from `data` at `offset`, zero-padding
/// if the data is shorter than `offset + 32`.
fn parse_word(data: &[u8], offset: usize) -> [u8; 32] {
let mut word = [0u8; 32];
if offset < data.len() {
let end = std::cmp::min(offset + 32, data.len());
let len = end - offset;
word[32 - len..].copy_from_slice(&data[offset..end]);
}
word
}
/// Parse a secp256k1 affine point from two consecutive 32-byte words at `offset`.
/// (0,0) is treated as the point at infinity.
fn parse_secp256k1_point(
data: &[u8],
offset: usize,
) -> Result<k256::ProjectivePoint, PrecompileError> {
use k256::elliptic_curve::sec1::FromEncodedPoint;
let x_bytes = parse_word(data, offset);
let y_bytes = parse_word(data, offset + 32);
let is_zero = x_bytes.iter().all(|&b| b == 0) && y_bytes.iter().all(|&b| b == 0);
if is_zero {
return Ok(k256::ProjectivePoint::IDENTITY);
}
let mut uncompressed = [0u8; 65];
uncompressed[0] = 0x04;
uncompressed[1..33].copy_from_slice(&x_bytes);
uncompressed[33..65].copy_from_slice(&y_bytes);
let encoded = k256::EncodedPoint::from_bytes(uncompressed)
.map_err(|_| PrecompileError::other("invalid secp256k1 point encoding"))?;
let affine = k256::AffinePoint::from_encoded_point(&encoded);
if affine.is_none().into() {
return Err(PrecompileError::other("point not on secp256k1 curve"));
}
Ok(k256::ProjectivePoint::from(affine.unwrap()))
}
/// Encode a projective point as 64 bytes [x(32) | y(32)].
/// The identity (point at infinity) encodes as all zeros.
fn encode_secp256k1_point(point: k256::ProjectivePoint) -> Vec<u8> {
use k256::elliptic_curve::sec1::ToEncodedPoint;
let affine = k256::AffinePoint::from(point);
let encoded = affine.to_encoded_point(false);
if encoded.is_identity() {
return vec![0u8; 64];
}
let mut out = vec![0u8; 64];
let x = encoded.x().expect("non-identity point has x");
let y = encoded.y().expect("non-identity point has y");
out[..32].copy_from_slice(x);
out[32..].copy_from_slice(y);
out
}
// ---------------------------------------------------------------------------
// BlockHeaderContract helpers
// ---------------------------------------------------------------------------
/// Compute the 4-byte ABI method selector (keccak256 of the signature).
fn selector_of(sig: &str) -> [u8; 4] {
use sha3::{Digest, Keccak256};
let h = Keccak256::digest(sig.as_bytes());
[h[0], h[1], h[2], h[3]]
}
#[derive(Debug)]
enum DepthError {
Overflow,
Negative,
}
/// Parse a 32-byte ABI-encoded int256 into an i16 depth value, matching rskj's
/// `shortValueExact()` semantics: values outside [-32768, 32767] return Overflow,
/// negative values return Negative.
fn parse_int256_as_depth(data: &[u8]) -> Result<i16, DepthError> {
let mut word = [0u8; 32];
let len = data.len().min(32);
word[32 - len..].copy_from_slice(&data[..len]);
// Check sign: int256 is two's complement, high bit indicates negative.
let is_negative = word[0] & 0x80 != 0;
if is_negative {
// Negative: all leading bytes must be 0xFF and the result must fit i16.
let all_ff = word[..30].iter().all(|&b| b == 0xFF);
if !all_ff {
return Err(DepthError::Negative);
}
let val = i16::from_be_bytes([word[30], word[31]]);
if val >= 0 {
// e.g. 0xFFFF...FF0001 → the i16 portion is positive, meaning
// the int256 value is very large negative; still negative.
return Err(DepthError::Negative);
}
Err(DepthError::Negative)
} else {
// Positive: all leading bytes must be 0x00 and result must fit i16.
let all_zero = word[..30].iter().all(|&b| b == 0);
if !all_zero {
return Err(DepthError::Overflow);
}
let val = i16::from_be_bytes([word[30], word[31]]);
if val < 0 {
// i16 overflowed (e.g. 0x0000...8000 = 32768 doesn't fit signed i16)
return Err(DepthError::Overflow);
}
Ok(val)
}
}
/// ABI-encode raw bytes as a Solidity `bytes` return value, replicating
/// ethereumj's `SolidityType.BytesType.encode`.
///
/// Layout: 32-byte offset (0x20) | 32-byte length | data (right-padded to 32).
///
/// ethereumj pads with `((len - 1) / 32 + 1) * 32` — Java's `-1/32 == 0`
/// makes EMPTY bytes pad to one full zero word (96 bytes total instead of
/// the canonical 64). The extra returndata word is consensus-visible
/// (RETURNDATACOPY copy gas): mainnet #1,669,062 calls
/// getCoinbaseAddress(4000) (≥ MAX_DEPTH → empty result) and rskj's reply
/// is 96 bytes.
fn abi_encode_bytes(data: &[u8]) -> Vec<u8> {
let padded_len = if data.is_empty() {
32
} else {
data.len().div_ceil(32) * 32
};
let mut out = vec![0u8; 64 + padded_len];
// offset → 0x20
out[31] = 0x20;
// length
let len_be = (data.len() as u64).to_be_bytes();
out[56..64].copy_from_slice(&len_be);
// data
out[64..64 + data.len()].copy_from_slice(data);
out
}
/// Convert a U256 to Java's `BigInteger.toByteArray()` format:
/// minimal big-endian two's complement with a leading 0x00 when the high bit
/// of the first data byte is set (to keep the value positive).
fn u256_to_java_bigint_bytes(val: U256) -> Vec<u8> {
if val.is_zero() {
return vec![0];
}
let be = val.to_be_bytes::<32>();
let start = be.iter().position(|&b| b != 0).unwrap_or(31);
let mut bytes = be[start..].to_vec();
if bytes[0] & 0x80 != 0 {
bytes.insert(0, 0);
}
bytes
}
/// Convert a u64 to Java's `BigInteger.valueOf(n).toByteArray()` format.
fn u64_to_java_bigint_bytes(val: u64) -> Vec<u8> {
u256_to_java_bigint_bytes(U256::from(val))
}
/// Minimal unsigned big-endian bytes (empty for zero) — the raw form of a
/// header RLP element. rskj's `GetGasLimit` returns `header.getGasLimit()`
/// verbatim (the decoded RLP bytes), so unlike the BigInteger-encoded fields
/// there is no 0x00 sign prefix when the high bit is set.
fn u256_to_raw_minimal_bytes(val: U256) -> Vec<u8> {
let be = val.to_be_bytes::<32>();
let start = be.iter().position(|&b| b != 0).unwrap_or(32);
be[start..].to_vec()
}
/// Extract merged mining tags from a block header's bitcoin coinbase tx.
///
/// Finds the last occurrence of `RSKBLOCK:` in the coinbase transaction,
/// skips past the 32-byte block header hash, and returns the remaining bytes.
fn extract_merged_mining_tags(header: &rustock_core::Header) -> Vec<u8> {
let coinbase_tx = match &header.bitcoin_merged_mining_coinbase_transaction {
Some(tx) => tx.as_ref(),
None => return Vec::new(),
};
// Find the last occurrence of RSK_TAG
let tag_pos = coinbase_tx
.windows(RSK_TAG.len())
.rposition(|w| w == RSK_TAG);
let tag_pos = match tag_pos {
Some(p) => p,
None => return Vec::new(),
};
let start = tag_pos + RSK_TAG.len() + RSK_TAG_HASH_SIZE;
if start >= coinbase_tx.len() {
return Vec::new();
}
coinbase_tx[start..].to_vec()
}
// ---------------------------------------------------------------------------
// HDWalletUtils ABI helpers
// ---------------------------------------------------------------------------
/// ABI-encode a string return value (identical layout to `abi_encode_bytes`).
fn abi_encode_string(s: &str) -> Vec<u8> {
abi_encode_bytes(s.as_bytes())
}
/// Read a big-endian uint256 from a 32-byte word, returning its value as usize.
/// Returns `None` if the value overflows usize.
fn abi_read_offset(data: &[u8], pos: usize) -> Option<usize> {
if pos + 32 > data.len() {
return None;
}
let word = &data[pos..pos + 32];
if word[..24].iter().any(|&b| b != 0) {
return None; // too large for usize
}
let mut buf = [0u8; 8];
buf.copy_from_slice(&word[24..32]);
Some(u64::from_be_bytes(buf) as usize)
}
/// ABI-decode a `bytes` parameter. `param_slot` is the 32-byte slot index
/// (0 for first param, 1 for second, etc.) within `data` (already past the selector).
fn abi_decode_bytes(data: &[u8], param_slot: usize) -> Option<Vec<u8>> {
let offset = abi_read_offset(data, param_slot * 32)?;
let length = abi_read_offset(data, offset)?;
let start = offset + 32;
if start + length > data.len() {
return None;
}
Some(data[start..start + length].to_vec())
}
/// ABI-decode a `string` parameter.
fn abi_decode_string(data: &[u8], param_slot: usize) -> Option<String> {
let bytes = abi_decode_bytes(data, param_slot)?;
String::from_utf8(bytes).ok()
}
/// ABI-decode a static `int256` parameter as i32. Returns `None` if
/// the value doesn't fit in i32.
fn abi_decode_int256_as_i32(data: &[u8], param_slot: usize) -> Option<i32> {
let pos = param_slot * 32;
if pos + 32 > data.len() {
return None;
}
let word = &data[pos..pos + 32];
let is_negative = word[0] & 0x80 != 0;
let fill = if is_negative { 0xFF } else { 0x00 };
if word[..28].iter().any(|&b| b != fill) {
return None;
}
let val = i32::from_be_bytes([word[28], word[29], word[30], word[31]]);
if is_negative && val >= 0 {
return None;
}
if !is_negative && val < 0 {
return None;
}
Some(val)
}
/// ABI-decode a `bytes[]` parameter.
fn abi_decode_bytes_array(data: &[u8], param_slot: usize) -> Option<Vec<Vec<u8>>> {
let array_offset = abi_read_offset(data, param_slot * 32)?;
let count = abi_read_offset(data, array_offset)?;
let mut items = Vec::with_capacity(count);
for i in 0..count {
let elem_rel_offset = abi_read_offset(data, array_offset + 32 + i * 32)?;
let elem_abs = array_offset + 32 + elem_rel_offset;
let elem_len = abi_read_offset(data, elem_abs)?;
let elem_start = elem_abs + 32;
if elem_start + elem_len > data.len() {
return None;
}
items.push(data[elem_start..elem_start + elem_len].to_vec());
}
Some(items)
}
// ---------------------------------------------------------------------------
// HDWalletUtils method implementations
// ---------------------------------------------------------------------------
/// `toBase58Check(bytes hash160, int256 version) → string`
///
/// Encodes a 20-byte hash with a version byte into a Base58Check string.
fn run_to_base58check(data: &[u8], gas_limit: u64) -> Result<PrecompileOutput, PrecompileError> {
const GAS_COST: u64 = 13_000;
if gas_limit < GAS_COST {
return Err(PrecompileError::OutOfGas);
}
let hash160 = abi_decode_bytes(data, 0)
.ok_or_else(|| PrecompileError::other("toBase58Check: cannot decode hash160"))?;
if hash160.len() != 20 {
return Err(PrecompileError::other("toBase58Check: Invalid hash160"));
}
let version = abi_decode_int256_as_i32(data, 1)
.ok_or_else(|| PrecompileError::other("toBase58Check: cannot decode version"))?;
if !(0..256).contains(&version) {
return Err(PrecompileError::other(
"toBase58Check: version must be a numeric value between 0 and 255",
));
}
let mut payload = Vec::with_capacity(21);
payload.push(version as u8);
payload.extend_from_slice(&hash160);
let encoded = bitcoin::base58::encode_check(&payload);
Ok(PrecompileOutput::new(GAS_COST, abi_encode_string(&encoded).into()))
}
/// `deriveExtendedPublicKey(string xpub, string path) → string`
///
/// Derives a child extended public key along a BIP32 path.
fn run_derive_extended_public_key(
data: &[u8],
gas_limit: u64,
) -> Result<PrecompileOutput, PrecompileError> {
const GAS_COST: u64 = 107_000;
if gas_limit < GAS_COST {
return Err(PrecompileError::OutOfGas);
}
let xpub_str = abi_decode_string(data, 0)
.ok_or_else(|| PrecompileError::other("deriveExtendedPublicKey: cannot decode xpub"))?;
let path_str = abi_decode_string(data, 1)
.ok_or_else(|| PrecompileError::other("deriveExtendedPublicKey: cannot decode path"))?;
let xpub = parse_xpub(&xpub_str)?;
validate_derivation_path(&path_str)?;
let child_numbers = parse_derivation_path(&path_str)?;
let secp = bitcoin::secp256k1::Secp256k1::verification_only();
let mut derived = xpub;
for child in &child_numbers {
derived = derived.ckd_pub(&secp, *child).map_err(|e| {
PrecompileError::other(format!("deriveExtendedPublicKey: derivation failed: {e}"))
})?;
}
let result_str = derived.to_string();
Ok(PrecompileOutput::new(GAS_COST, abi_encode_string(&result_str).into()))
}
/// `extractPublicKeyFromExtendedPublicKey(string xpub) → bytes`
///
/// Returns the 33-byte compressed public key from an extended public key.
fn run_extract_pubkey(data: &[u8], gas_limit: u64) -> Result<PrecompileOutput, PrecompileError> {
const GAS_COST: u64 = 11_300;
if gas_limit < GAS_COST {
return Err(PrecompileError::OutOfGas);
}
let xpub_str = abi_decode_string(data, 0).ok_or_else(|| {
PrecompileError::other("extractPublicKeyFromExtendedPublicKey: cannot decode xpub")
})?;
let xpub = parse_xpub(&xpub_str)?;
let pubkey_bytes = xpub.public_key.serialize();
Ok(PrecompileOutput::new(GAS_COST, abi_encode_bytes(&pubkey_bytes).into()))
}
/// `getMultisigScriptHash(int256 minimumSignatures, bytes[] publicKeys) → bytes`
///
/// Builds a P2SH multisig redeem script and returns RIPEMD160(SHA256(script)).
fn run_get_multisig_script_hash(
data: &[u8],
gas_limit: u64,
) -> Result<PrecompileOutput, PrecompileError> {
use k256::elliptic_curve::sec1::FromEncodedPoint;
const BASE_COST: u64 = 20_000;
const COST_PER_EXTRA_KEY: u64 = 700;
let min_sigs = abi_decode_int256_as_i32(data, 0)
.ok_or_else(|| PrecompileError::other("getMultisigScriptHash: cannot decode minimumSignatures"))?;
let public_keys = abi_decode_bytes_array(data, 1);
let public_keys = match public_keys {
Some(keys) => keys,
None => {
return Err(PrecompileError::other("getMultisigScriptHash: At least 2 public keys are required"));
}
};
let gas_cost = if public_keys.len() >= 2 {
BASE_COST + (public_keys.len() as u64 - 2) * COST_PER_EXTRA_KEY
} else {
BASE_COST
};
if gas_limit < gas_cost {
return Err(PrecompileError::OutOfGas);
}
if min_sigs <= 0 {
return Err(PrecompileError::other(
"getMultisigScriptHash: Minimum required signatures must be present and greater than zero",
));
}
if public_keys.len() < 2 {
return Err(PrecompileError::other(
"getMultisigScriptHash: At least 2 public keys are required",
));
}
if public_keys.len() < min_sigs as usize {
return Err(PrecompileError::other(
"getMultisigScriptHash: public keys are less than the minimum required signatures",
));
}
if public_keys.len() > 15 {
return Err(PrecompileError::other(
"getMultisigScriptHash: public keys are more than the maximum allowed signatures",
));
}
let mut compressed_keys: Vec<[u8; 33]> = Vec::with_capacity(public_keys.len());
for key_bytes in &public_keys {
if key_bytes.len() != 33 && key_bytes.len() != 65 {
return Err(PrecompileError::other(format!(
"getMultisigScriptHash: Invalid public key length: {}",
key_bytes.len()
)));
}
let prefix = key_bytes[0];
if prefix != 0x02 && prefix != 0x03 && prefix != 0x04 {
return Err(PrecompileError::other("getMultisigScriptHash: Invalid public key format"));
}
let compressed = if key_bytes.len() == 33 {
let mut arr = [0u8; 33];
arr.copy_from_slice(key_bytes);
// Validate the key is on the curve
let encoded = k256::EncodedPoint::from_bytes(key_bytes)
.map_err(|_| PrecompileError::other("getMultisigScriptHash: Invalid public key format"))?;
let pt = k256::AffinePoint::from_encoded_point(&encoded);
if pt.is_none().into() {
return Err(PrecompileError::other("getMultisigScriptHash: Invalid public key format"));
}
arr
} else {
// 65-byte uncompressed: validate and compress
let encoded = k256::EncodedPoint::from_bytes(key_bytes)
.map_err(|_| PrecompileError::other("getMultisigScriptHash: Invalid public key format"))?;
let pt = k256::AffinePoint::from_encoded_point(&encoded);
if pt.is_none().into() {
return Err(PrecompileError::other("getMultisigScriptHash: Invalid public key format"));
}
let affine = pt.unwrap();
let comp = k256::EncodedPoint::from(affine);
let comp_bytes = comp.compress().to_bytes();
let mut arr = [0u8; 33];
arr.copy_from_slice(&comp_bytes);
arr
};
compressed_keys.push(compressed);
}
// Sort keys by compressed bytes (matches bitcoinj's createRedeemScript behavior)
compressed_keys.sort();
// Build multisig redeem script:
// OP_m <pubkey1> <pubkey2> ... <pubkeyn> OP_n OP_CHECKMULTISIG
let mut script = Vec::new();
script.push(0x50 + min_sigs as u8); // OP_m
for key in &compressed_keys {
script.push(33); // OP_PUSHBYTES_33
script.extend_from_slice(key);
}
script.push(0x50 + compressed_keys.len() as u8); // OP_n
script.push(0xAE); // OP_CHECKMULTISIG
// RIPEMD160(SHA256(script))
use sha2::Digest as Sha2Digest;
let sha256_hash = sha2::Sha256::digest(&script);
let script_hash = ripemd::Ripemd160::digest(sha256_hash);
Ok(PrecompileOutput::new(gas_cost, abi_encode_bytes(&script_hash).into()))
}
/// Parse an xpub/tpub string into a `bitcoin::bip32::Xpub`.
fn parse_xpub(xpub_str: &str) -> Result<bitcoin::bip32::Xpub, PrecompileError> {
if !xpub_str.starts_with("xpub") && !xpub_str.starts_with("tpub") {
return Err(PrecompileError::other(format!(
"Invalid extended public key '{xpub_str}'"
)));
}
xpub_str
.parse::<bitcoin::bip32::Xpub>()
.map_err(|e| PrecompileError::other(format!("Invalid extended public key '{xpub_str}': {e}")))
}
/// Validate a BIP32 derivation path string per rskj rules:
/// - Non-empty, starts and ends with a digit
/// - No `M` prefix, no hardening `'`, no negative numbers
/// - Each segment < 2^31, at most 10 segments
fn validate_derivation_path(path: &str) -> Result<(), PrecompileError> {
if path.is_empty() {
return Err(PrecompileError::other("Invalid path"));
}
let first_char = path.chars().next().unwrap();
let last_char = path.chars().last().unwrap();
if !first_char.is_ascii_digit() || !last_char.is_ascii_digit() {
return Err(PrecompileError::other("Invalid path"));
}
let chunks: Vec<&str> = path.split('/').collect();
if chunks.len() > 10 {
return Err(PrecompileError::other("Path should contain 10 levels at most"));
}
for chunk in &chunks {
if chunk.contains('\'') || chunk.contains('H') {
return Err(PrecompileError::other("Invalid path"));
}
match chunk.parse::<i64>() {
Ok(n) if (0..(1i64 << 31)).contains(&n) => {}
_ => return Err(PrecompileError::other("Invalid path")),
}
}
Ok(())
}
/// Parse a validated path string into ChildNumber values.
fn parse_derivation_path(
path: &str,
) -> Result<Vec<bitcoin::bip32::ChildNumber>, PrecompileError> {
path.split('/')
.map(|s| {
let idx: u32 = s
.parse()
.map_err(|_| PrecompileError::other("Invalid path"))?;
bitcoin::bip32::ChildNumber::from_normal_idx(idx)
.map_err(|_| PrecompileError::other("Invalid path"))
})
.collect()
}
// ---------------------------------------------------------------------------
// Precompile set builder
// ---------------------------------------------------------------------------
/// Builds the complete revm `Precompiles` set for an RSK block.
///
/// Starts with the Ethereum precompiles matching the block's SpecId,
/// then adds RSK-specific precompiles gated by their activation RSKIPs.
pub fn rsk_precompiles(hardfork_cfg: &RskHardforkConfig, block_number: u64) -> Precompiles {
let upgrade = hardfork_cfg.active_upgrade(block_number);
// rskj gates each precompile on its own RSKIP rather than Ethereum spec
// buckets (PrecompiledContracts.getContractForAddress). From genesis:
// 0x01-0x04 (ecrecover, sha256, ripemd160, identity) plus 0x05 modexp
// with EIP-198 (Byzantium) pricing.
let mut precompiles = Precompiles::new(PrecompileSpecId::HOMESTEAD).clone();
precompiles.extend([revm::precompile::modexp::BYZANTIUM]);
// RSKIP137 (Papyrus200): BN128 add/mul/pairing, priced per EIP-1108
// (Istanbul: 150 / 6000 / 45000 + 34000 per pair) from activation.
if upgrade >= RskNetworkUpgrade::Papyrus200 {
precompiles.extend([
revm::precompile::bn254::add::ISTANBUL,
revm::precompile::bn254::mul::ISTANBUL,
revm::precompile::bn254::pair::ISTANBUL,
]);
}
// RSKIP153 (Iris300): Blake2F
if upgrade >= RskNetworkUpgrade::Iris300 {
precompiles.extend([revm::precompile::blake2::FUN]);
}
// Genesis precompiles: Bridge, REMASC (always active)
precompiles.extend([
Precompile::new(
PrecompileId::custom("rsk-remasc"),
REMASC_ADDR,
remasc_run,
),
Precompile::new(
PrecompileId::custom("rsk-bridge"),
BRIDGE_ADDR,
bridge_run,
),
]);
// RSKIP106 (Wasabi100): HDWalletUtils
if upgrade >= RskNetworkUpgrade::Wasabi100 {
precompiles.extend([
Precompile::new(
PrecompileId::custom("rsk-hdwallet"),
HD_WALLET_UTILS_ADDR,
hd_wallet_utils_run,
),
]);
}
// RSKIP119 (Wasabi100): BlockHeaderContract
if upgrade >= RskNetworkUpgrade::Wasabi100 {
precompiles.extend([
Precompile::new(
PrecompileId::custom("rsk-blockheader"),
BLOCK_HEADER_ADDR,
block_header_run,
),
]);
}
// RSKIP203 (Arrowhead600): Environment
if upgrade >= RskNetworkUpgrade::Arrowhead600 {
precompiles.extend([
Precompile::new(
PrecompileId::custom("rsk-environment"),
ENVIRONMENT_ADDR,
environment_run,
),
]);
}
// RSKIP516 (Reed800): Secp256k1 Addition/Multiplication
if upgrade >= RskNetworkUpgrade::Reed800 {
precompiles.extend([
Precompile::new(
PrecompileId::custom("rsk-secp256k1-add"),
SECP256K1_ADD_ADDR,
secp256k1_add_run,
),
Precompile::new(
PrecompileId::custom("rsk-secp256k1-mul"),
SECP256K1_MUL_ADDR,
secp256k1_mul_run,
),
]);
}
precompiles
}
// ---------------------------------------------------------------------------
// PrecompileProvider implementation for revm integration
// ---------------------------------------------------------------------------
/// Context about the currently-executing transaction, used by Bridge precompile.
///
/// The Bridge's `releaseBtc` method needs:
/// - The RSK tx hash (for RSKIP146 release queue format)
/// - The BTC destination hash160 (derived from the sender's compressed pubkey)
///
/// This context is set by the executor before each `transact_one` call and
/// read by the Bridge precompile inside `run_bridge`.
#[derive(Debug, Clone, Default)]
pub struct BridgeTxContext {
/// Keccak256 of the RLP-encoded transaction.
pub rsk_tx_hash: [u8; 32],
/// BTC P2PKH destination: RIPEMD160(SHA256(compressed_pubkey)).
/// Derived from the RSK transaction's secp256k1 signature.
/// Zero bytes if the pubkey cannot be recovered (system/REMASC transactions).
pub btc_sender_hash160: [u8; 20],
/// RSK sender address of the executing transaction (Bridge event payloads).
pub rsk_sender: Address,
/// Whether this is a *local* call -- rskj's `Transaction.isLocalCall`,
/// set by `ReversibleTransactionExecutor` (the `eth_call`/`estimateGas`
/// path) via `TransactionExecutor.setLocalCall(true)`.
///
/// Bridge methods marked `LocalOnly` execute only for such a call and
/// throw for anything on-chain (`Bridge.validateLocalCall`,
/// Bridge.java:431). It is false for every transaction in a block, so it
/// can never change consensus; it only decides whether a read-only query
/// over RPC is answered or rejected.
pub local_call: bool,
/// Position of this transaction in its block. Not consensus -- it exists
/// so a recorded Bridge decision can be located afterwards, and is zero
/// outside block execution.
pub tx_index: u32,
}
/// RSKIP197 (iris300): the `requiredGas` (rskj `getGasForData`) charged to a
/// failing precompile CALL whose error is a *non-OOG* exception. Post-197 such
/// a call costs exactly this amount (the surplus forwarded gas is refunded and
/// execution continues with a `0` pushed) — `Program.executePrecompiledAndHandleError`
/// runs `refundGas(msg.gas - requiredGas)` in its `finally` block.
///
/// Two families reach this path. The standard ETH precompiles that revm reports
/// a non-OOG `Err` for at iris: BN128 add/mul/pairing (0x06–0x08, throw on an
/// invalid point post-RSKIP197 — `BN128PrecompiledContract.unsafeExecute`) and
/// BLAKE2F (0x09, throws on a bad final-block byte or bad input length —
/// `Blake2F.execute`). For BN128 the non-OOG `Err` is only returned after revm's
/// internal `gas_used <= gas_limit` check, so `requiredGas <= gas_limit` always
/// holds, matching rskj.
///
/// And, from reed800, the RSK secp256k1 precompiles (RSKIP516), which return a
/// non-OOG `Err` whenever a point is off-curve or a coordinate is >= p. rskj
/// charges their fixed cost regardless, because `getGasForData` never looks at
/// the input.
///
/// Returns `None` only for addresses that genuinely never reach the non-OOG
/// error path; `None` becomes 0 gas at the call site, so an omission here is a
/// silent undercharge rather than a failure.
fn rskip197_required_gas_on_error(addr: &Address, input: &[u8]) -> Option<u64> {
// EIP-1108 / Istanbul pricing, active for BN128 from papyrus200 in rskj
// (BN128Addition/Multiplication/Pairing.getGasForData).
const BN128_ADD: Address = Address::new(hex_addr("0000000000000000000000000000000000000006"));
const BN128_MUL: Address = Address::new(hex_addr("0000000000000000000000000000000000000007"));
const BN128_PAIR: Address = Address::new(hex_addr("0000000000000000000000000000000000000008"));
const BLAKE2F: Address = Address::new(hex_addr("0000000000000000000000000000000000000009"));
const BN128_PAIR_SIZE: usize = 192;
match *addr {
BN128_ADD => Some(150),
BN128_MUL => Some(6_000),
BN128_PAIR => Some(45_000 + 34_000 * (input.len() / BN128_PAIR_SIZE) as u64),
// Blake2F.getGasForData: malformed length -> 0 (can't read rounds);
// otherwise the big-endian u32 rounds count (rskj F_ROUND == 1).
BLAKE2F if input.len() == 213 => Some(u32::from_be_bytes(
input[..4].try_into().expect("len checked == 213"),
) as u64),
BLAKE2F => Some(0),
// RSKIP516 (reed800). rskj's Secp256k1Addition/Multiplication return
// their fixed cost from getGasForData REGARDLESS of whether the input
// parses, so an off-curve point still costs 150 / 3000. Omitting them
// here charged 0, because the caller does `.unwrap_or(0)`.
SECP256K1_ADD_ADDR => Some(150),
SECP256K1_MUL_ADDR => Some(3_000),
_ => None,
}
}
/// Wraps an owned `Precompiles` set to implement revm's `PrecompileProvider`.
///
/// Unlike `EthPrecompiles` which holds a `&'static Precompiles`, this owns the
/// set because RSK precompiles are dynamically built per-block based on which
/// RSKIPs are active.
pub struct RskPrecompileProvider {
precompiles: Precompiles,
hardfork_cfg: RskHardforkConfig,
spec: SpecId,
block_store: Option<Arc<BlockStore>>,
remasc_config: RemascConfig,
bridge_config: BridgeConstants,
/// Shared slot for per-transaction context used by Bridge precompile.
/// Updated by the executor before each `transact_one`.
bridge_tx_context: std::sync::Arc<std::sync::Mutex<BridgeTxContext>>,
/// Set when a direct Bridge call hits rskj's invisible-exception path
/// (parse failure post-RSKIP88). `RskHandler` reads it during fee
/// finalization: no leftover refund, REMASC gets gasLimit * gasPrice.
/// Cleared by `RskHandler::load_accounts` before each transaction.
invisible_exception: std::sync::Arc<std::sync::atomic::AtomicBool>,
/// Precompiles successfully called during the current transaction. rskj
/// writes the contract storage-prefix marker (`setupContract`) on every
/// successful precompile call; the executor drains this after each tx and
/// applies the markers to the trie if the tx committed.
called_precompiles: std::sync::Arc<std::sync::Mutex<Vec<Address>>>,
/// Set when this transaction reaches REMASC or the Bridge. See
/// [`RskPrecompileProvider::reached_sequential_only_slot`].
reached_sequential_only: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl std::fmt::Debug for RskPrecompileProvider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RskPrecompileProvider")
.field("hardfork_cfg", &self.hardfork_cfg)
.field("spec", &self.spec)
.field("block_store", &self.block_store.as_ref().map(|_| "BlockStore"))
.finish()
}
}
impl RskPrecompileProvider {
/// Returns the shared bridge tx context Arc, allowing the executor to update
/// per-transaction context before each `transact_one` call.
pub fn bridge_tx_context_slot(&self) -> std::sync::Arc<std::sync::Mutex<BridgeTxContext>> {
std::sync::Arc::clone(&self.bridge_tx_context)
}
/// Returns the shared invisible-exception flag for `RskHandler`.
pub fn invisible_exception_flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {