Repository navigation
Expand file tree
/
Copy pathpeg.rs
More file actions
7933 lines (7409 loc) · 364 KB
/
Copy pathpeg.rs
File metadata and controls
7933 lines (7409 loc) · 364 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
//! Peg-in and peg-out logic for the Bridge.
//!
//! ## Peg-in (`registerBtcTransaction`)
//!
//! The core flow:
//! 1. Verify BTC transaction is included in a stored block (via PMT)
//! 2. Check the block has sufficient confirmations
//! 3. Classify the transaction (peg-in / migration / etc.)
//! 4. For peg-in: identify the federation address in outputs, credit RBTC
//! 5. Mark the transaction as processed
//!
//! ## Peg-out (`releaseBtc`)
//!
//! Enqueues a release request that will be processed by `updateCollections`.
//!
//! ## Release request queue formats (rskj BridgeSerializationUtils)
//!
//! Pre-RSKIP146 (`releaseRequestQueue`):
//! RLP_list [ btc_addr_hash160_0, bigint(sat_0), btc_addr_hash160_1, bigint(sat_1), ... ]
//!
//! Post-RSKIP146 (`releaseRequestQueueWithTxHash`):
//! RLP_list [ btc_addr_hash160_0, bigint(sat_0), rsk_tx_hash_0, ... ] (triples)
//!
//! ## rskTxsWaitingFS (pegoutsWaitingForSignatures)
//!
//! SortedMap<keccak256_rsk_tx_hash → raw_btc_tx_bytes> stored as:
//! RLP_list [ rlp_bytes(rsk_hash_0), rlp_bytes(btc_tx_raw_0), rlp_bytes(rsk_hash_1), ... ]
use alloy_primitives::{Address as RskAddress, Bytes, U256};
use bitcoin::consensus::{deserialize, serialize as btc_serialize};
use bitcoin::hashes::Hash;
use bitcoin::Transaction as BtcTransaction;
use revm::context_interface::{ContextTr, JournalTr};
use revm::precompile::{PrecompileError, PrecompileOutput};
use std::collections::BTreeMap;
use sha2;
use ripemd;
use super::btc_store::load_chain_head;
use super::constants::BridgeConstants;
use super::pmt::PartialMerkleTree;
use super::serialization::{rlp_decode_list, rlp_encode_element, rlp_encode_list, rlp_encode_u64};
use super::storage::*;
use super::tx::*;
use crate::hardfork::RskHardforkConfig;
use crate::precompiles::{BRIDGE_ADDR, BridgeTxContext};
use crate::silent::{FieldValue, SilentKind};
/// rskj `BridgeSupport.BURN_ADDRESS`: receiver of the sBTC burned when a
/// pegout's dusty change output is raised to the non-dust minimum.
const BURN_ADDR: RskAddress = RskAddress::new([0xff; 20]);
/// A pending peg-out release request, matching rskj's ReleaseRequestQueue.Entry.
///
/// The BTC destination address is the P2PKH hash160 derived from the RSK
/// transaction sender's public key (matching rskj's BridgeUtils.recoverBtcAddressFromEthTransaction).
#[derive(Debug, Clone)]
pub struct ReleaseRequest {
/// BTC destination address as 20-byte P2PKH hash160.
pub btc_dest_hash160: [u8; 20],
/// Amount in satoshis (NOT wei).
pub amount_satoshis: u64,
/// RSK transaction hash (post-RSKIP146 only; None for pre-RSKIP146 queue).
pub rsk_tx_hash: Option<[u8; 32]>,
}
// ---------------------------------------------------------------------------
// registerBtcTransaction
// ---------------------------------------------------------------------------
/// `registerBtcTransaction(bytes btcTxSerialized, int256 height, bytes pmtSerialized)`
///
/// The core peg-in method. Verifies a BTC transaction is included in the
/// BTC header chain, classifies it, and credits RBTC to the sender.
/// rskj BridgeSupport.shouldMarkRejectedPeginAsProcessed: only between
/// RSKIP459 (lovell700) and RSKIP551 (vetiver900) are rejected
/// non-refundable peg-ins marked as processed.
fn should_mark_rejected_pegin_as_processed(cfg: &RskHardforkConfig, block_number: u64) -> bool {
cfg.has_rskip459(block_number) && !cfg.has_rskip551(block_number)
}
/// rskj `PegUtilsLegacy.isValidPegInTx` minimum gate over the live-federations
/// outputs. Under RSKIP293 each UTXO must be at least `min`
/// (`isAnyUTXOAmountBelowMinimum`); before it, the *total* sent must be
/// (`valueSentToMe.isLessThan`). An EMPTY set of live-fed outputs is not below
/// minimum under RSKIP293 (`anyMatch` over an empty stream is false), so a tx
/// that pays no live federation is still a valid (amount-0) peg-in; pre-RSKIP293
/// a 0 total is below minimum and is not a peg-in.
fn pegin_below_minimum(live_output_values: &[u64], min: u64, rskip293: bool) -> bool {
if rskip293 {
live_output_values.iter().any(|v| *v < min)
} else {
live_output_values.iter().sum::<u64>() < min
}
}
pub fn register_btc_transaction<CTX: crate::RskContextTr>(
ctx: &mut CTX,
args: &[u8],
gas_cost: u64,
config: &BridgeConstants,
hardfork_cfg: &RskHardforkConfig,
tx_ctx: &BridgeTxContext,
) -> Result<PrecompileOutput, PrecompileError> {
if args.len() < 96 {
return Err(PrecompileError::other(
"registerBtcTransaction: args too short",
));
}
// Parse ABI arguments:
// arg0: bytes btcTxSerialized (dynamic)
// arg1: int256 height
// arg2: bytes pmtSerialized (dynamic)
let btc_tx_offset = U256::from_be_slice(&args[0..32]).to::<usize>();
let btc_block_height = {
let raw = U256::from_be_slice(&args[32..64]);
raw.to::<u64>()
};
let pmt_offset = U256::from_be_slice(&args[64..96]).to::<usize>();
let btc_tx_data = read_dynamic_bytes(args, btc_tx_offset)?;
let pmt_data = read_dynamic_bytes(args, pmt_offset)?;
// Compute BTC tx hash
let btc_tx_hash = calculate_btc_tx_hash(&btc_tx_data);
// A fresh bridge BTC store must be seeded with the rskj checkpoint
// before any chain lookups.
let block_number = revm::context_interface::Block::number(ctx.block()).to::<u64>();
let use_v2 = hardfork_cfg.has_stored_block_v2(block_number);
let rskip199 = hardfork_cfg.has_rskip199(block_number);
super::btc_chain::ensure_btc_chain_seeded(ctx, config, use_v2, rskip199);
// rskj wraps the registerBtcTransaction body in
// `try { ... } catch (RegisterBtcTransactionException e) { log }`: an
// already-processed tx or any failed validation
// (validationsForRegisterBtcTransaction → "Could not validate
// transaction") is logged and the call returns SUCCESSFULLY without
// registering anything. Mirror that — these are a no-op success, not a
// failed tx. Only a malformed BTC tx (parsed below, a separate
// exception) propagates and fails the tx.
// rskj's validation failures are NOT all equivalent, and treating them as
// if they were diverged mainnet #9,227,292.
//
// `BridgeSupport.registerBtcTransaction` wraps its body in
// `catch (RegisterBtcTransactionException e) { log }`, so a validation that
// *returns false* is a silent no-op success. But
// `validationsForRegisterBtcTransaction` also **throws**
// `BridgeIllegalArgumentException` for a malformed partial merkle tree, and
// that is not a `RegisterBtcTransactionException` -- it escapes the catch,
// reaches `Bridge.execute`'s outer handler, becomes a `VMException`, and
// charges the sender the full gas limit (quirks-frozen-bugs.md §9d).
//
// Order is load-bearing too: rskj validates height and confirmations FIRST
// and returns false there, so a transaction with bad confirmations *and* a
// malformed PMT is swallowed, never reaching the throw.
enum Invalid {
/// `return false` in rskj: logged, call succeeds, nothing registered.
Swallowed(&'static str),
/// `throw BridgeIllegalArgumentException`: escapes the catch and fails
/// the transaction with the full gas limit charged.
Thrown(&'static str),
}
let validation = (|| -> Result<(), Invalid> {
// Check if already processed (rskj: RegisterBtcTransactionException).
if is_btc_tx_processed(ctx, &btc_tx_hash) {
return Err(Invalid::Swallowed("transaction already processed"));
}
// Height and confirmations come first, and are swallowed
// (BridgeUtils.validateHeightAndConfirmations -> return false). The
// block itself counts as one confirmation, and the CALLER-supplied
// height is what gets validated.
let best_height = load_chain_head(ctx).map(|h| h.height).unwrap_or(0);
let confirmations = best_height as i64 - btc_block_height as i64 + 1;
if confirmations < config.btc2rsk_minimum_acceptable_confirmations as i64 {
return Err(Invalid::Swallowed("insufficient confirmations"));
}
// PMT size: rskj THROWS BridgeIllegalArgumentException here.
if !PartialMerkleTree::has_expected_size(&pmt_data) {
return Err(Invalid::Thrown("PartialMerkleTree doesn't have expected size"));
}
// `BridgeUtils.calculateMerkleRoot` constructs the PMT and walks it;
// a VerificationException from either is rethrown as
// BridgeIllegalArgumentException, so both of these throw.
let pmt = PartialMerkleTree::parse(&pmt_data)
.ok_or(Invalid::Thrown("failed to parse PMT"))?;
let pmt_result = pmt
.extract_matches()
.ok_or(Invalid::Thrown("PMT verification failed"))?;
// Tx not among the matched hashes: `calculateMerkleRoot` returns null,
// so the caller returns false -- swallowed.
if !pmt_result.matched_hashes.contains(&btc_tx_hash) {
return Err(Invalid::Swallowed("tx not in PMT"));
}
// Look up the BTC block on the main chain at the caller-supplied
// height (walks the chain pre-RSKIP199, indexed lookup afterwards).
let stored_block =
super::btc_chain::stored_block_at_main_chain_height(ctx, btc_block_height as u32, rskip199)
.ok_or(Invalid::Swallowed("BTC block not found at height"))?;
let block_hash = stored_block.header.block_hash();
// Verify merkle root matches
let block_merkle_root = {
let raw = stored_block.header.merkle_root.to_raw_hash();
*raw.as_byte_array()
};
let root_valid = if pmt_result.merkle_root == block_merkle_root {
true
} else {
// Post-RSKIP143: also accept witness merkle root. The coinbase
// information is keyed by the block hash in DISPLAY byte order
// (rskj `Sha256Hash.toString()`; see set_coinbase_information),
// the reverse of rust-bitcoin's internal order.
let block_hash_bytes = {
let mut raw = *block_hash.to_raw_hash().as_byte_array();
raw.reverse();
raw
};
match get_coinbase_information(ctx, &block_hash_bytes) {
// The stored witness merkle root is in DISPLAY byte order
// (rskj registerBtcCoinbaseTransaction wraps the ABI arg and
// reverses it for the commitment, BridgeSupport l.2574), while
// the PMT merkle root is internal order — compare reversed.
Some(mut witness_root) => {
witness_root.reverse();
pmt_result.merkle_root == witness_root
}
None => false,
}
};
if !root_valid {
return Err(Invalid::Swallowed("merkle root mismatch"));
}
Ok(())
})();
match validation {
Ok(()) => {}
Err(Invalid::Swallowed(m)) => {
tracing::debug!(
"registerBtcTransaction: {m}; returning success \
(rskj swallows RegisterBtcTransactionException)"
);
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
}
Err(Invalid::Thrown(m)) => {
tracing::debug!(
"registerBtcTransaction: {m}; throwing \
(rskj BridgeIllegalArgumentException escapes the catch)"
);
return Err(PrecompileError::other(m));
}
}
// Parse the BTC transaction
let btc_tx: BtcTransaction = deserialize(&btc_tx_data).map_err(|_| {
PrecompileError::other("registerBtcTransaction: invalid BTC transaction")
})?;
// rskj re-checks "already processed" using the witness-stripped txid
// (BridgeSupport.registerBtcTransaction l.404, `btcTx.getHash(false)`):
// the pre-parse check above used the wtxid (`calculateBtcTxHash` over the
// raw bytes), so for a SegWit tx the two keys differ and this second check
// is what actually guards the legacy-txid-keyed map. Every mark below uses
// this same legacy txid (rskj markTxAsProcessed l.763).
let legacy_txid = legacy_btc_txid(&btc_tx);
if is_btc_tx_processed(ctx, &legacy_txid) {
tracing::debug!("registerBtcTransaction: transaction already processed (txid); returning success");
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
}
// Live federations (active + retiring during migration): their P2SH
// scripts identify which outputs are peg-ins and which inputs make the
// tx a peg-out (rskj getNoSpendWalletForLiveFederations).
let block_number_now = revm::context_interface::Block::number(ctx.block()).to::<u64>();
// Each live federation's redeem script (and hence the P2SH address used to
// recognize peg-in outputs / peg-out inputs) is built from its STORED format
// version, not the current block — an ERP federation keeps its ERP script
// even after a later template hardfork (rskj getActiveFederation /
// getRetiringFederation → Federation.getRedeemScript()).
let (federation_keys, fed_redeem) =
active_federation_keys_and_redeem(ctx, config, hardfork_cfg, block_number_now);
// getActiveFederationAddress is format-aware: a P2SH-P2WSH (format 4000,
// RSKIP305) federation is recognized at its P2SH-P2WSH address, so peg-in /
// UTXO-registration output matching must use that script, not a plain P2SH.
let active_format = active_federation_format(ctx, config, hardfork_cfg, block_number_now);
let fed_script = p2sh_output_script(&federation_output_hash160(&fed_redeem, active_format));
// rskj isPegOutTx compares against each federation's STANDARD redeem script
// (getStandardRedeemScript) — for an ERP federation this is the default
// multisig branch only, not the full ERP/flyover-wrapped redeem.
let fed_standard_redeem =
build_federation_redeem_script(&federation_keys, federation_keys.len() / 2 + 1);
let retiring_format =
federation_format_version(ctx, super::storage::OLD_FEDERATION_FORMAT_VERSION_KEY);
let retiring = retiring_federation_keys_and_redeem(ctx, config, hardfork_cfg, block_number_now)
.map(|(_keys, redeem)| {
let script = p2sh_output_script(&federation_output_hash160(&redeem, retiring_format));
(redeem, script)
});
let retiring_standard_redeem = retiring_federation_keys(ctx, config, hardfork_cfg, block_number_now)
.map(|keys| build_federation_redeem_script(&keys, keys.len() / 2 + 1));
// rskj marks processed txs with the RSK execution block number
// (BridgeSupport.markTxAsProcessed), not the BTC block height.
let rsk_height = revm::context_interface::Block::number(ctx.block()).to::<u64>();
// Attribute anything this call records, including from helpers several
// frames down that have no block of their own.
crate::silent::set_position(rsk_height, tx_ctx.tx_index);
// RSKIP419: an SVP fund/spend transaction is recognized by its
// signature-stripped txid matching the stored unsigned hash. rskj's
// PegUtils.getTransactionType checks this BEFORE the pegin/pegout
// classification; the matched tx is handled by registerSvpFundTx /
// registerSvpSpendTx (= registerNewUtxos + the SVP state transition) and
// nothing else.
if hardfork_cfg.has_rskip419(rsk_height) {
if let Some(without_sigs) = multisig_txid_without_signatures(&btc_tx) {
let fund_hash = super::serialization::rlp_decode_element(&bridge_load_bytes_named(
ctx,
super::storage::SVP_FUND_TX_HASH_UNSIGNED_KEY,
));
let spend_hash = super::serialization::rlp_decode_element(&bridge_load_bytes_named(
ctx,
super::storage::SVP_SPEND_TX_HASH_UNSIGNED_KEY,
));
let is_fund = fund_hash.as_deref() == Some(&without_sigs[..]);
let is_spend = spend_hash.as_deref() == Some(&without_sigs[..]);
if is_fund || is_spend {
// registerNewUtxos: register outputs paying the active (and
// retiring) federation, then mark the tx processed.
let active_utxo_key =
active_federation_utxo_key(ctx, config, hardfork_cfg, rsk_height);
register_federation_outputs(ctx, &btc_tx, &fed_script, active_utxo_key);
if let Some((_, retiring_script)) = &retiring {
register_federation_outputs(
ctx,
&btc_tx,
retiring_script,
super::storage::OLD_FEDERATION_BTC_UTXOS_KEY,
);
}
if is_fund {
// registerSvpFundTx: if the SVP window is still open, record
// the signed fund tx and clear its unsigned hash.
if svp_is_ongoing(ctx, config, rsk_height) {
bridge_store_bytes_named(
ctx,
super::storage::SVP_FUND_TX_SIGNED_KEY,
&super::serialization::rlp_encode_element(&btc_serialize(&btc_tx)),
);
bridge_store_bytes_named(
ctx,
super::storage::SVP_FUND_TX_HASH_UNSIGNED_KEY,
&[],
);
}
} else {
// registerSvpSpendTx: clear the spend hash and commit the
// proposed federation (the real handover).
bridge_store_bytes_named(
ctx,
super::storage::SVP_SPEND_TX_HASH_UNSIGNED_KEY,
&[],
);
super::governance::commit_proposed_federation(ctx, config, hardfork_cfg);
}
record_pegin(
SilentKind::BtcTxMarkedProcessed,
&btc_tx,
tx_ctx,
0,
if is_fund { "SVP_FUND_TX" } else { "SVP_SPEND_TX" },
vec![],
);
set_btc_tx_processed(
ctx,
&legacy_txid,
rsk_height,
hardfork_cfg.has_rskip134(rsk_height),
);
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
}
}
}
// Minimum peg-in value (legacy until RSKIP219, strictly-below comparison
// per PegUtilsLegacy.isValidPegInTx). Needed both for the migration
// moveToActive check below and the peg-in value gate further down.
let min_pegin = if hardfork_cfg.has_rskip219(rsk_height) {
config.minimum_pegin_tx_value
} else {
config.legacy_minimum_pegin_tx_value
};
// rskj PegUtilsLegacy.getTransactionType — PEGOUT_OR_MIGRATION detection.
// An input "spends" a federation when its scriptSig redeem hashes to that
// federation's P2SH; isPegOutTx/migration compare the input's STANDARD
// (default-branch) redeem (extractStandardRedeemScript) to each fed's
// standard P2SH, while txIsFromOldFederation compares the FULL redeem.
let active_std_hash160 = redeem_script_hash160(&fed_standard_redeem);
let retiring_std_hash160 = retiring_standard_redeem.as_ref().map(|r| redeem_script_hash160(r));
// lastRetiredFederationP2SHScript (RSKIP186): the P2SH of the last fully
// retired federation, stored as serializeScript = RLP([program]).
let retired_hash160: Option<[u8; 20]> = if hardfork_cfg.has_rskip186(rsk_height) {
let raw = super::storage::bridge_load_bytes_named(
ctx,
super::storage::LAST_RETIRED_FEDERATION_P2SH_SCRIPT_KEY,
);
rlp_decode_list(&raw)
.and_then(|items| items.into_iter().next())
.filter(|p| p.len() == 23)
.map(|p| p[2..22].try_into().expect("23-byte P2SH program"))
} else {
None
};
// rskj `PegUtilsLegacy.isPegOutTx` builds BOTH `createP2SHOutputScript` and
// (post-RSKIP305) `createP2SHP2WSHOutputScript` of the input's STANDARD
// redeem and matches either against each federation's
// `getFederationStandardP2SHScript` (`getDefaultP2SHScript`, which is the
// P2SH-P2WSH form for a segwit federation). The input's standard redeem is
// the same redeem the federation stored, so checking the input's legacy AND
// witness-program hashes against a federation's stored hash matches it
// whichever form that hash was stored in (a segwit retired/retiring/active
// fed stores the witness-program hash; #8,569,377).
let has_rskip305 = hardfork_cfg.has_rskip305(rsk_height);
let input_matches_fed = |full: &[u8], target: [u8; 20]| -> bool {
let std = build_federation_redeem_script(
&super::release_tx::spending_redeem_keys(full),
super::release_tx::redeem_script_threshold(full),
);
redeem_script_hash160(&std) == target
|| (has_rskip305 && federation_output_hash160(&std, 4000) == target)
};
// rskj `BitcoinUtils.extractRedeemScriptFromInput`: a segwit (P2SH-P2WSH)
// input carries its redeem in the witness (last item), not the scriptSig
// (which is just the witness-program push) — so classification must read it
// from there to recognize a segwit peg-out/migration.
let input_redeem = |i: &bitcoin::TxIn| -> Option<Vec<u8>> {
if !i.witness.is_empty() {
i.witness.last().map(|r| r.to_vec())
} else {
super::release_tx::extract_redeem_script(i.script_sig.as_bytes())
}
};
// (1) txIsFromOldFederation (RSKIP199): any input spends the hardcoded old
// federation address — unconditionally a migration.
let tx_from_old_fed = hardfork_cfg.has_rskip199(rsk_height)
&& btc_tx.input.iter().any(|i| {
input_redeem(i)
.is_some_and(|r| redeem_script_hash160(&r) == config.old_federation_address_hash160)
});
// (4) isPegOutTx(liveFeds): an input's standard redeem matches the active
// or retiring federation.
let spends_live_fed = btc_tx.input.iter().any(|i| {
input_redeem(i).is_some_and(|r| {
input_matches_fed(&r, active_std_hash160)
|| retiring_std_hash160.is_some_and(|t| input_matches_fed(&r, t))
})
});
// (3) isMigrationTx: an input spends the retired or retiring federation AND
// an output funds the active federation (moveFromRetiringOrRetired &&
// moveToActive).
let spends_retired_or_retiring = btc_tx.input.iter().any(|i| {
input_redeem(i).is_some_and(|r| {
retired_hash160.is_some_and(|t| input_matches_fed(&r, t))
|| retiring_std_hash160.is_some_and(|t| input_matches_fed(&r, t))
})
});
let active_output_values: Vec<u64> = btc_tx
.output
.iter()
.filter(|o| o.script_pubkey == fed_script)
.map(|o| o.value.to_sat())
.collect();
let move_to_active = if hardfork_cfg.has_rskip293(rsk_height) {
!active_output_values.is_empty() && active_output_values.iter().all(|v| *v >= min_pegin)
} else {
active_output_values.iter().sum::<u64>() >= min_pegin
};
let is_migration = spends_retired_or_retiring && move_to_active;
if tx_from_old_fed || is_migration || spends_live_fed {
record_pegin(
SilentKind::BtcTxMarkedProcessed,
&btc_tx,
tx_ctx,
active_output_values.iter().sum(),
if tx_from_old_fed {
"FROM_OLD_FEDERATION"
} else if is_migration {
"MIGRATION"
} else {
"PEGOUT"
},
vec![],
);
let active_utxo_key = active_federation_utxo_key(ctx, config, hardfork_cfg, rsk_height);
register_federation_outputs(ctx, &btc_tx, &fed_script, active_utxo_key);
if let Some((_, retiring_script)) = &retiring {
register_federation_outputs(
ctx,
&btc_tx,
retiring_script,
super::storage::OLD_FEDERATION_BTC_UTXOS_KEY,
);
}
set_btc_tx_processed(ctx, &legacy_txid, rsk_height, hardfork_cfg.has_rskip134(rsk_height));
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
}
// Peg-in value: the outputs paying any live federation
// (rskj computeTotalAmountSent over the live-federations wallet).
let pays_live_federation = |script: &bitcoin::ScriptBuf| {
*script == fed_script || retiring.as_ref().is_some_and(|(_, rs)| *script == *rs)
};
let live_output_values: Vec<u64> = btc_tx
.output
.iter()
.filter(|o| pays_live_federation(&o.script_pubkey))
.map(|o| o.value.to_sat())
.collect();
let total_value: u64 = live_output_values.iter().sum();
// rskj PegUtilsLegacy.isValidPegInTx minimum gate: under RSKIP293 it checks
// EACH UTXO (isAnyUTXOAmountBelowMinimum), otherwise the total amount sent
// (valueSentToMe.isLessThan). Crucially, an EMPTY live-output set is not
// "below minimum" under RSKIP293 (anyMatch over an empty stream is false),
// so a tx that pays no live federation (e.g. only a now-retired one, once
// the retiring federation has been cleared earlier in the block) is still a
// valid peg-in — processed with amount 0 (pegin_btc amount=0, destination
// account created). Pre-RSKIP293 a 0 total is below minimum → not a peg-in.
let rskip379 = hardfork_cfg.has_rskip379(rsk_height);
// RSKIP379 (Arrowhead600) moves the minimum-value gate to
// `PegUtils.allUTXOsToFedAreAboveMinimumPeginValue`, which EXPLICITLY rejects
// an empty fed-output set (`if (fedUtxos.isEmpty()) return false;`). So an
// empty (or any-below-minimum) set is below minimum — the OPPOSITE of the
// pre-379 legacy rule where `anyMatch`/`!isAnyUTXOAmountBelowMinimum` is
// vacuously satisfied by an empty set (a valid amount-0 peg-in, #5,171,600).
let below_min = if rskip379 {
live_output_values.is_empty() || live_output_values.iter().any(|&v| v < min_pegin)
} else {
pegin_below_minimum(&live_output_values, min_pegin, hardfork_cfg.has_rskip293(rsk_height))
};
if below_min {
// Pre-RSKIP379: rskj getTransactionType returns UNKNOWN (neither a
// migration nor a peg-out), so registerBtcTransaction ignores it silently.
// Post-RSKIP379: evaluatePegin returns (NO_REFUND, INVALID_AMOUNT), and
// BridgeSupport.handleNonRefundablePegin logs rejected_pegin(INVALID_AMOUNT=5)
// then unrefundable_pegin(NonRefundablePeginReason.INVALID_AMOUNT=3); it
// marks the tx processed only when shouldMarkRejectedPeginAsProcessed
// (RSKIP459 && !RSKIP551 — not yet active at Arrowhead600).
record_pegin(
SilentKind::PeginRejectedNoRefund,
&btc_tx,
tx_ctx,
total_value,
"INVALID_AMOUNT",
vec![
("minimumSat", FieldValue::U64(min_pegin)),
("fedOutputs", FieldValue::U64(live_output_values.len() as u64)),
// Whether the chain also logged this. Before RSKIP379 it did
// not, which is the gap these records exist to fill.
("logged", FieldValue::Flag(rskip379)),
],
);
if rskip379 {
let hash = btc_txid_event_bytes(&btc_tx);
super::events::log_rejected_pegin(ctx, &hash, 5);
super::events::log_unrefundable_pegin(ctx, &hash, 3);
}
if should_mark_rejected_pegin_as_processed(hardfork_cfg, rsk_height) {
set_btc_tx_processed(ctx, &legacy_txid, rsk_height, hardfork_cfg.has_rskip134(rsk_height));
}
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
}
// Sender classification (rskj BtcLockSenderProvider). Used by the legacy
// (v0) path for the destination/refund, and as the v1 fallback refund.
let sender = match classify_pegin_sender(&btc_tx) {
Ok(s) => s,
Err(why) => {
// rskj raises an uncaught RuntimeException on this input;
// Bridge.execute catches it, panics and rethrows as VMException, so
// the whole registerBtcTransaction call fails. Failing here is what
// keeps the two nodes agreeing.
return Err(PrecompileError::other(format!(
"registerBtcTransaction: rskj aborts on this scriptSig ({why})"
)));
}
};
// Announce any peg-in that depended on the sender-detection path this node
// intends to remove, so the operator hears about it before the RSKIP lands
// rather than after. Single-key senders -- P2PKH and P2SH-P2WPKH, the ones
// that can actually be credited -- are silent.
if let Some((shape, hash160)) = match &sender {
Some(PeginSender::P2shMultisig { p2sh_hash }) => Some(("P2SH-multisig", *p2sh_hash)),
Some(PeginSender::P2shP2wsh { p2sh_hash }) => Some(("P2SH-P2WSH", *p2sh_hash)),
_ => None,
} {
super::rskj_sender_compat::report(&super::rskj_sender_compat::Sighting {
block: rsk_height,
btc_txid: hex::encode(legacy_txid),
shape,
refund_hash160: hex::encode(hash160),
});
}
// rskj `PeginInformation.parse`: the BtcLockSender sets the default
// (version-0) info; then, if RSKIP170 is active, an RSKT OP_RETURN
// overrides it (version 1). A malformed RSKT payload throws
// `PeginInstructionsException` and rejects the v1 peg-in. NoOpReturn
// (Ok(None)) leaves the legacy info in place.
let instructions = if hardfork_cfg.has_rskip170(rsk_height) {
match super::pegin_instructions::build_pegin_instructions(&btc_tx) {
Ok(opt) => opt,
Err(_) => {
// processPegIn: parse exception. RSKIP181 logs
// PEGIN_V1_INVALID_PAYLOAD(4); refund to the sender (the only
// refund address available — a malformed payload has no v1
// refund), then mark processed.
if hardfork_cfg.has_rskip181(rsk_height) {
super::events::log_rejected_pegin(ctx, &btc_txid_event_bytes(&btc_tx), 4);
}
match &sender {
Some(s) => {
let (h, p2sh) = sender_refund_target(s);
let mut extra = refund_fields(&h, p2sh, config);
extra.push((
"senderType",
FieldValue::Text(sender_type_name(Some(s)).into()),
));
extra.push(("peginVersion", FieldValue::U64(1)));
extra.push((
"logged",
FieldValue::Flag(hardfork_cfg.has_rskip181(rsk_height)),
));
record_pegin(
SilentKind::PeginRefunded,
&btc_tx,
tx_ctx,
total_value,
"PEGIN_V1_INVALID_PAYLOAD",
extra,
);
}
None => record_pegin(
SilentKind::PeginRejectedNoRefund,
&btc_tx,
tx_ctx,
total_value,
"PEGIN_V1_INVALID_PAYLOAD",
vec![
("logged", FieldValue::Flag(hardfork_cfg.has_rskip181(rsk_height))),
("senderType", FieldValue::Text("UNDETERMINED".into())),
("peginVersion", FieldValue::U64(1)),
],
),
}
if let Some(sender) = &sender {
let (refund_hash160, refund_is_p2sh) = sender_refund_target(sender);
emit_pegin_rejection_release(
ctx, &btc_tx, &refund_hash160, refund_is_p2sh, total_value, &fed_redeem,
&retiring, &pays_live_federation, rsk_height, config, hardfork_cfg, tx_ctx,
);
}
set_btc_tx_processed(ctx, &legacy_txid, rsk_height, hardfork_cfg.has_rskip134(rsk_height));
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
}
}
} else {
None
};
let cap_ok = |ctx: &mut CTX| {
!hardfork_cfg.has_rskip134(rsk_height)
|| verify_lock_does_not_surpass_locking_cap(ctx, config, total_value)
};
let rbtc_amount = btc_satoshi_to_rbtc_wei(total_value);
// ---- Version 1 (RSKIP170 OP_RETURN) peg-in ----
if let Some(instr) = instructions {
// processPegInVersion1: NO whitelist, only the locking cap.
if !cap_ok(ctx) {
if hardfork_cfg.has_rskip181(rsk_height) {
super::events::log_rejected_pegin(ctx, &btc_txid_event_bytes(&btc_tx), 1); // PEGIN_CAP_SURPASSED
}
// refundTxSender: refund to the v1 refund address if present, else
// the BtcLockSender address; if neither, no refund (a non-refundable
// peg-in — unrefundable_pegin event not modeled, see TODO).
match v1_refund_target(&instr, sender.as_ref()) {
Some((h, p2sh)) => {
let mut extra = refund_fields(&h, p2sh, config);
extra.push((
"senderType",
FieldValue::Text(sender_type_name(sender.as_ref()).into()),
));
extra.push(("peginVersion", FieldValue::U64(1)));
// Whether the refund address came from the OP_RETURN or
// fell back to the sender -- the RSKIP distinguishes them.
extra.push((
"refundFromPayload",
FieldValue::Flag(instr.btc_refund_address.is_some()),
));
extra.push(("logged", FieldValue::Flag(hardfork_cfg.has_rskip181(rsk_height))));
record_pegin(
SilentKind::PeginRefunded,
&btc_tx,
tx_ctx,
total_value,
"PEGIN_CAP_SURPASSED",
extra,
);
}
None => record_pegin(
SilentKind::PeginRejectedNoRefund,
&btc_tx,
tx_ctx,
total_value,
"PEGIN_CAP_SURPASSED",
vec![
("logged", FieldValue::Flag(hardfork_cfg.has_rskip181(rsk_height))),
("senderType", FieldValue::Text("UNDETERMINED".into())),
("peginVersion", FieldValue::U64(1)),
],
),
}
if let Some((refund_hash160, refund_is_p2sh)) = v1_refund_target(&instr, sender.as_ref()) {
emit_pegin_rejection_release(
ctx, &btc_tx, &refund_hash160, refund_is_p2sh, total_value, &fed_redeem,
&retiring, &pays_live_federation, rsk_height, config, hardfork_cfg, tx_ctx,
);
}
set_btc_tx_processed(ctx, &legacy_txid, rsk_height, hardfork_cfg.has_rskip134(rsk_height));
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
}
// executePegIn: credit the v1 destination from the OP_RETURN payload.
let dest = RskAddress::from(instr.rsk_destination);
if !rbtc_amount.is_zero() {
let _ = ctx.journal_mut().transfer(BRIDGE_ADDR, dest, rbtc_amount);
} else {
// transferTo(dest, 0) still creates+persists the account (RSK keeps
// empty touched accounts — see the legacy path below).
let _ = ctx.journal_mut().load_account(dest);
ctx.journal_mut().touch_account(dest);
}
// RSKIP170 is required for v1, so pegin_btc (protocolVersion = 1).
super::events::log_pegin_btc(ctx, dest, &btc_txid_event_bytes(&btc_tx), total_value, 1);
record_pegin(
SilentKind::PeginAccepted,
&btc_tx,
tx_ctx,
total_value,
"ACCEPTED",
vec![
("destination", FieldValue::Addr(dest)),
("senderType", FieldValue::Text(sender_type_name(sender.as_ref()).into())),
("peginVersion", FieldValue::U64(1)),
("logged", FieldValue::Flag(true)),
],
);
let active_utxo_key = active_federation_utxo_key(ctx, config, hardfork_cfg, rsk_height);
register_federation_outputs(ctx, &btc_tx, &fed_script, active_utxo_key);
if let Some((_, retiring_script)) = &retiring {
register_federation_outputs(ctx, &btc_tx, retiring_script, super::storage::OLD_FEDERATION_BTC_UTXOS_KEY);
}
set_btc_tx_processed(ctx, &legacy_txid, rsk_height, hardfork_cfg.has_rskip134(rsk_height));
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
}
// ---- Version 0 (legacy) peg-in ----
// A non-P2PKH sender before RSKIP143 (txIsProcessable) aborts WITHOUT
// marking the tx as processed (no BtcLockSender or unsupported type).
let Some(sender) = sender else {
// rskj `PegUtils.evaluateLegacyPegin` default case (PegUtils.java:256):
// an undetermined sender type (no BtcLockSender) →
// (NO_REFUND, LEGACY_PEGIN_UNDETERMINED_SENDER). Post-RSKIP379
// `handleNonRefundablePegin` logs rejected_pegin(LEGACY_PEGIN_UNDETERMINED_SENDER=3)
// then unrefundable_pegin(NonRefundablePeginReason.LEGACY_PEGIN_UNDETERMINED_SENDER=1),
// and marks the tx processed only when RSKIP459 && !RSKIP551. Pre-379 the
// legacy path aborts silently (sender could not be determined).
record_pegin(
SilentKind::PeginRejectedNoRefund,
&btc_tx,
tx_ctx,
total_value,
"LEGACY_PEGIN_UNDETERMINED_SENDER",
vec![
// Post-RSKIP379 this path logs rejected_pegin then
// unrefundable_pegin; pre-379 it aborts silently.
("logged", FieldValue::Flag(hardfork_cfg.has_rskip379(rsk_height))),
("senderType", FieldValue::Text("UNDETERMINED".into())),
("inputShape", FieldValue::Text(undetermined_input_shape(&btc_tx).into())),
(
"scriptSigLen",
FieldValue::U64(
btc_tx
.input
.first()
.map(|i| i.script_sig.as_bytes().len() as u64)
.unwrap_or(0),
),
),
(
"witnessItems",
FieldValue::U64(
btc_tx.input.first().map(|i| i.witness.len() as u64).unwrap_or(0),
),
),
("peginVersion", FieldValue::U64(0)),
("logged", FieldValue::Flag(hardfork_cfg.has_rskip379(rsk_height))),
],
);
if hardfork_cfg.has_rskip379(rsk_height) {
let hash = btc_txid_event_bytes(&btc_tx);
super::events::log_rejected_pegin(ctx, &hash, 3);
super::events::log_unrefundable_pegin(ctx, &hash, 1);
if should_mark_rejected_pegin_as_processed(hardfork_cfg, rsk_height) {
set_btc_tx_processed(ctx, &legacy_txid, rsk_height, hardfork_cfg.has_rskip134(rsk_height));
}
}
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
};
let rskip143 = hardfork_cfg.has_rskip143(rsk_height);
if !matches!(sender, PeginSender::P2pkh { .. }) && !rskip143 {
// Dropped without a refund, without being marked processed and
// without a log line of any kind: the quietest outcome the Bridge has.
record_pegin(
SilentKind::PeginRejectedNoRefund,
&btc_tx,
tx_ctx,
total_value,
"SENDER_NOT_PROCESSABLE_PRE_RSKIP143",
vec![
("senderType", FieldValue::Text(sender_type_name(Some(&sender)).into())),
("peginVersion", FieldValue::U64(0)),
("logged", FieldValue::Flag(false)),
("markedProcessed", FieldValue::Flag(false)),
],
);
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
}
// rskj txIsLockable: only P2PKH and (post-RSKIP143) P2SH-P2WPKH senders
// can lock; other processable types are refunded ("Btc tx type not
// supported, returning funds to sender") without consulting the
// whitelist or the locking cap.
let (sender_hash160, sender_is_p2sh, sender_pubkey, lockable): ([u8; 20], bool, Option<&[u8]>, bool) =
match &sender {
PeginSender::P2pkh { pubkey } => (pubkey_hash160(pubkey), false, Some(pubkey), true),
PeginSender::P2shP2wpkh { pubkey, p2sh_hash } => {
(*p2sh_hash, true, Some(pubkey), true)
}
PeginSender::P2shMultisig { p2sh_hash } | PeginSender::P2shP2wsh { p2sh_hash } => {
(*p2sh_hash, true, None, false)
}
};
// Lock whitelist gate (rskj verifyLockSenderIsWhitelisted): the matching
// one-off entry is consumed on success; rejection generates a refund
// peg-out back to the sender (generateRejectionRelease).
// Locking cap gate (rskj verifyLockDoesNotSurpassLockingCap, RSKIP134):
// evaluated only when the whitelist passed (rskj short-circuits the &&,
// so a whitelist rejection never lazily initializes the cap). A cap
// rejection produces the same refund release as a whitelist one.
let allowed = lockable
&& whitelist_allows_and_consume(
ctx,
&sender_hash160,
total_value,
btc_block_height,
hardfork_cfg.has_rskip87(rsk_height),
)
&& cap_ok(ctx);
tracing::debug!(
"pegin lock check: sender {} amount {} btc_height {} -> {}",
to_hex(&sender_hash160),
total_value,
btc_block_height,
allowed
);
if !allowed {
// RSKIP181 (iris300): log rejected_pegin. rskj processPegInVersionLegacy
// re-runs the lockable/cap checks in the rejection branch (NOT the
// whitelist): `!isTxLockableForLegacyVersion` -> LEGACY_PEGIN_MULTISIG_SENDER(2),
// else `!verifyLockDoesNotSurpassLockingCap` -> PEGIN_CAP_SURPASSED(1).
// A whitelist-only rejection (lockable, cap ok) logs nothing. The cap
// re-evaluation here also lazily initializes the locking-cap cell, like
// rskj's second verifyLockDoesNotSurpassLockingCap call.
//
// The silent reason is read off this same evaluation rather than
// recomputed: `cap_ok` WRITES (it lazily initializes the locking-cap
// cell), so calling it a second time -- or calling it pre-RSKIP181,
// where rskj does not -- would change the state root. A diagnostic
// that alters what it observes is worse than no diagnostic.
let silent_reason;
if hardfork_cfg.has_rskip181(rsk_height) {
let reason = if !lockable {
silent_reason = "LEGACY_PEGIN_MULTISIG_SENDER";
Some(2u64) // LEGACY_PEGIN_MULTISIG_SENDER
} else if !cap_ok(ctx) {
silent_reason = "PEGIN_CAP_SURPASSED";
Some(1u64) // PEGIN_CAP_SURPASSED
} else {
silent_reason = "LOCK_WHITELIST_REJECTED";
None // whitelist rejection: no event
};
if let Some(reason) = reason {
super::events::log_rejected_pegin(ctx, &btc_txid_event_bytes(&btc_tx), reason);
}
} else if !lockable {
silent_reason = "LEGACY_PEGIN_MULTISIG_SENDER";
} else if crate::silent::is_recording()
&& hardfork_cfg.has_rskip134(rsk_height)
&& !locking_cap_would_allow(ctx, config, total_value)
{
// Pre-RSKIP181 rskj does not re-evaluate the cap here, so the
// reason is established by a read-only equivalent rather than by
// the real check, which writes. Guarded on recording only to skip
// the reads when nobody wants the answer -- it changes nothing.
//
// Gated on RSKIP134 as `cap_ok` is: before papyrus200 no locking
// cap exists, so the cell is unset and the read-only equivalent
// would fall back to `initial_locking_cap` and could blame a cap
// that was not yet a rule. In that era the only way to reach this
// branch is a lock-whitelist rejection, which is the one thing a
// pre-papyrus200 replay exists to find.
silent_reason = "PEGIN_CAP_SURPASSED";
} else {
silent_reason = "LOCK_WHITELIST_REJECTED";
}
let mut extra = refund_fields(&sender_hash160, sender_is_p2sh, config);
extra.push(("senderType", FieldValue::Text(sender_type_name(Some(&sender)).into())));
extra.push(("peginVersion", FieldValue::U64(0)));
extra.push((
"logged",
FieldValue::Flag(
hardfork_cfg.has_rskip181(rsk_height)
&& silent_reason != "LOCK_WHITELIST_REJECTED",
),
));
record_pegin(SilentKind::PeginRefunded, &btc_tx, tx_ctx, total_value, silent_reason, extra);
emit_pegin_rejection_release(
ctx, &btc_tx, &sender_hash160, sender_is_p2sh, total_value, &fed_redeem,
&retiring, &pays_live_federation, rsk_height, config, hardfork_cfg, tx_ctx,
);
set_btc_tx_processed(ctx, &legacy_txid, rsk_height, hardfork_cfg.has_rskip134(rsk_height));
return Ok(PrecompileOutput::new(gas_cost, Bytes::new()));
}
// RSK destination: rskj's legacy peg-in credits the address derived from
// the sender's public key (ethereumj ECKey.getAddress over the
// UNCOMPRESSED point — mainnet #267,460 used a 65-byte pubkey).
let rsk_destination = sender_pubkey.and_then(super::federation::rsk_address_from_public_key);
// Credit the derived destination address (transfer from Bridge balance)
if let Some(dest) = rsk_destination {
if !rbtc_amount.is_zero() {
let _ = ctx.journal_mut().transfer(BRIDGE_ADDR, dest, rbtc_amount);
} else {
// rskj executePegIn always calls transferTo(dest, amount); a 0-value
// transfer still creates and persists the destination account (RSK
// keeps empty touched accounts — no EIP-161 cleanup). An amount-0
// peg-in therefore materializes the destination with balance 0.
let _ = ctx.journal_mut().load_account(dest);
ctx.journal_mut().touch_account(dest);
}
// Peg-in events: lock_btc from RSKIP146, pegin_btc from RSKIP170
// (a legacy peg-in past RSKIP170 logs pegin_btc with protocolVersion 0).
let txid_bytes = btc_txid_event_bytes(&btc_tx);
record_pegin(
SilentKind::PeginAccepted,
&btc_tx,
tx_ctx,
total_value,
"ACCEPTED",
vec![
("destination", FieldValue::Addr(dest)),
("senderType", FieldValue::Text(sender_type_name(Some(&sender)).into())),
(
"senderAddress",
FieldValue::Text(sender_base58_address(&sender_hash160, sender_is_p2sh, config)),
),
("peginVersion", FieldValue::U64(0)),
// `logged` is PER TOPIC, and the topic reconstructed for an
// accepted peg-in is `pegin_btc` -- so the test is RSKIP170,
// not RSKIP146.
//
// Between papyrus200 and iris300 the Bridge logs `lock_btc`
// instead. That peg-in is therefore visible in the real index