From 3dd68dd3e8d649008d6a7fdca56d96ec00fa9c9f Mon Sep 17 00:00:00 2001 From: Jeff Bencin Date: Sat, 4 Jan 2025 21:16:39 -0500 Subject: [PATCH 01/17] chore: Apply Clippy lint `vec_init_then_push` --- .../chainstate/nakamoto/coordinator/tests.rs | 99 +++++++++---------- stackslib/src/net/api/tests/postblock_v3.rs | 32 ++---- 2 files changed, 59 insertions(+), 72 deletions(-) diff --git a/stackslib/src/chainstate/nakamoto/coordinator/tests.rs b/stackslib/src/chainstate/nakamoto/coordinator/tests.rs index e0b3375452..862c2cad04 100644 --- a/stackslib/src/chainstate/nakamoto/coordinator/tests.rs +++ b/stackslib/src/chainstate/nakamoto/coordinator/tests.rs @@ -3234,54 +3234,53 @@ fn test_stacks_on_burnchain_ops() { let (mut burn_ops, mut tenure_change, miner_key) = peer.begin_nakamoto_tenure(TenureChangeCause::BlockFound); - let mut new_burn_ops = vec![]; - new_burn_ops.push(BlockstackOperationType::DelegateStx(DelegateStxOp { - sender: addr.clone(), - delegate_to: recipient_addr.clone(), - reward_addr: None, - delegated_ustx: 1, - until_burn_height: None, - - // mocked - txid: Txid([i; 32]), - vtxindex: 11, - block_height: block_height + 1, - burn_header_hash: BurnchainHeaderHash([0x00; 32]), - })); - new_burn_ops.push(BlockstackOperationType::StackStx(StackStxOp { - sender: addr.clone(), - reward_addr: PoxAddress::Standard( - recipient_addr.clone(), - Some(AddressHashMode::SerializeP2PKH), - ), - stacked_ustx: 1, - num_cycles: 1, - signer_key: Some(StacksPublicKeyBuffer::from_public_key( - &StacksPublicKey::from_private(&recipient_private_key), - )), - max_amount: Some(1), - auth_id: Some(i as u32), - - // mocked - txid: Txid([i | 0x80; 32]), - vtxindex: 12, - block_height: block_height + 1, - burn_header_hash: BurnchainHeaderHash([0x00; 32]), - })); - new_burn_ops.push(BlockstackOperationType::TransferStx(TransferStxOp { - sender: addr.clone(), - recipient: recipient_addr.clone(), - transfered_ustx: 1, - memo: vec![0x2], - - // mocked - txid: Txid([i | 0x40; 32]), - vtxindex: 13, - block_height: block_height + 1, - burn_header_hash: BurnchainHeaderHash([0x00; 32]), - })); - new_burn_ops.push(BlockstackOperationType::VoteForAggregateKey( - VoteForAggregateKeyOp { + let mut new_burn_ops = vec![ + BlockstackOperationType::DelegateStx(DelegateStxOp { + sender: addr.clone(), + delegate_to: recipient_addr.clone(), + reward_addr: None, + delegated_ustx: 1, + until_burn_height: None, + + // mocked + txid: Txid([i; 32]), + vtxindex: 11, + block_height: block_height + 1, + burn_header_hash: BurnchainHeaderHash([0x00; 32]), + }), + BlockstackOperationType::StackStx(StackStxOp { + sender: addr.clone(), + reward_addr: PoxAddress::Standard( + recipient_addr.clone(), + Some(AddressHashMode::SerializeP2PKH), + ), + stacked_ustx: 1, + num_cycles: 1, + signer_key: Some(StacksPublicKeyBuffer::from_public_key( + &StacksPublicKey::from_private(&recipient_private_key), + )), + max_amount: Some(1), + auth_id: Some(i as u32), + + // mocked + txid: Txid([i | 0x80; 32]), + vtxindex: 12, + block_height: block_height + 1, + burn_header_hash: BurnchainHeaderHash([0x00; 32]), + }), + BlockstackOperationType::TransferStx(TransferStxOp { + sender: addr.clone(), + recipient: recipient_addr.clone(), + transfered_ustx: 1, + memo: vec![0x2], + + // mocked + txid: Txid([i | 0x40; 32]), + vtxindex: 13, + block_height: block_height + 1, + burn_header_hash: BurnchainHeaderHash([0x00; 32]), + }), + BlockstackOperationType::VoteForAggregateKey(VoteForAggregateKeyOp { sender: addr.clone(), aggregate_key: StacksPublicKeyBuffer::from_public_key( &StacksPublicKey::from_private(&agg_private_key), @@ -3298,8 +3297,8 @@ fn test_stacks_on_burnchain_ops() { vtxindex: 14, block_height: block_height + 1, burn_header_hash: BurnchainHeaderHash([0x00; 32]), - }, - )); + }), + ]; extra_burn_ops.push(new_burn_ops.clone()); burn_ops.append(&mut new_burn_ops); diff --git a/stackslib/src/net/api/tests/postblock_v3.rs b/stackslib/src/net/api/tests/postblock_v3.rs index 0b0a95f3a4..0cd5f7b33e 100644 --- a/stackslib/src/net/api/tests/postblock_v3.rs +++ b/stackslib/src/net/api/tests/postblock_v3.rs @@ -178,19 +178,12 @@ fn handle_req_accepted() { |_| true, ); let next_block_id = next_block.block_id(); - let mut requests = vec![]; - - // post the block - requests.push(StacksHttpRequest::new_post_block_v3( - addr.into(), - &next_block, - )); - - // idempotent - requests.push(StacksHttpRequest::new_post_block_v3( - addr.into(), - &next_block, - )); + let requests = vec![ + // post the block + StacksHttpRequest::new_post_block_v3(addr.into(), &next_block), + // idempotent + StacksHttpRequest::new_post_block_v3(addr.into(), &next_block), + ]; let mut responses = rpc_test.run(requests); @@ -229,10 +222,8 @@ fn handle_req_without_trailing_accepted() { |_| true, ); let next_block_id = next_block.block_id(); - let mut requests = vec![]; - - // post the block - requests.push( + let requests = vec![ + // post the block StacksHttpRequest::new_for_peer( addr.into(), "POST".into(), @@ -240,10 +231,7 @@ fn handle_req_without_trailing_accepted() { HttpRequestContents::new().payload_stacks(&next_block), ) .unwrap(), - ); - - // idempotent - requests.push( + // idempotent StacksHttpRequest::new_for_peer( addr.into(), "POST".into(), @@ -251,7 +239,7 @@ fn handle_req_without_trailing_accepted() { HttpRequestContents::new().payload_stacks(&next_block), ) .unwrap(), - ); + ]; let mut responses = rpc_test.run(requests); let response = responses.remove(0); From d8be6a26d17877491b659d516dfbb7a608dfef40 Mon Sep 17 00:00:00 2001 From: Jeff Bencin Date: Sat, 4 Jan 2025 21:42:48 -0500 Subject: [PATCH 02/17] chore: Apply Clippy lint `iter_kv_map` --- stackslib/src/burnchains/affirmation.rs | 2 +- stackslib/src/burnchains/db.rs | 4 ++-- stackslib/src/chainstate/stacks/miner.rs | 6 +---- stackslib/src/net/atlas/download.rs | 8 +++---- .../nakamoto/download_state_machine.rs | 3 +-- stackslib/src/net/inv/nakamoto.rs | 4 ++-- stackslib/src/net/mod.rs | 24 +++++++++---------- stackslib/src/net/relay.rs | 11 ++++----- 8 files changed, 27 insertions(+), 35 deletions(-) diff --git a/stackslib/src/burnchains/affirmation.rs b/stackslib/src/burnchains/affirmation.rs index 88ad745800..9f97e37dc9 100644 --- a/stackslib/src/burnchains/affirmation.rs +++ b/stackslib/src/burnchains/affirmation.rs @@ -679,7 +679,7 @@ pub fn read_parent_block_commits( } } } - let mut parent_list: Vec<_> = parents.into_iter().map(|(_, cmt)| cmt).collect(); + let mut parent_list: Vec<_> = parents.into_values().collect(); parent_list.sort_by(|a, b| { if a.block_height != b.block_height { a.block_height.cmp(&b.block_height) diff --git a/stackslib/src/burnchains/db.rs b/stackslib/src/burnchains/db.rs index 1f42881ac2..30d52f5039 100644 --- a/stackslib/src/burnchains/db.rs +++ b/stackslib/src/burnchains/db.rs @@ -1245,8 +1245,8 @@ impl BurnchainDB { ops.extend( pre_stx_ops - .into_iter() - .map(|(_, op)| BlockstackOperationType::PreStx(op)), + .into_values() + .map(BlockstackOperationType::PreStx), ); ops.sort_by_key(|op| op.vtxindex()); diff --git a/stackslib/src/chainstate/stacks/miner.rs b/stackslib/src/chainstate/stacks/miner.rs index eae3e1f14d..235d9e0f8e 100644 --- a/stackslib/src/chainstate/stacks/miner.rs +++ b/stackslib/src/chainstate/stacks/miner.rs @@ -262,11 +262,7 @@ pub struct MinerEpochInfo<'a> { impl From<&UnconfirmedState> for MicroblockMinerRuntime { fn from(unconfirmed: &UnconfirmedState) -> MicroblockMinerRuntime { - let considered = unconfirmed - .mined_txs - .iter() - .map(|(txid, _)| txid.clone()) - .collect(); + let considered = unconfirmed.mined_txs.keys().cloned().collect(); MicroblockMinerRuntime { bytes_so_far: unconfirmed.bytes_so_far, prev_microblock_header: unconfirmed.last_mblock.clone(), diff --git a/stackslib/src/net/atlas/download.rs b/stackslib/src/net/atlas/download.rs index f877a0da3a..07e9a6cbd4 100644 --- a/stackslib/src/net/atlas/download.rs +++ b/stackslib/src/net/atlas/download.rs @@ -533,8 +533,8 @@ impl AttachmentsBatchStateContext { } let mut events_ids = results .faulty_peers - .iter() - .map(|(k, _)| *k) + .keys() + .map(|k| *k) .collect::>(); self.events_to_deregister.append(&mut events_ids); @@ -567,8 +567,8 @@ impl AttachmentsBatchStateContext { } let mut events_ids = results .faulty_peers - .iter() - .map(|(k, _)| *k) + .keys() + .map(|k| *k) .collect::>(); self.events_to_deregister.append(&mut events_ids); diff --git a/stackslib/src/net/download/nakamoto/download_state_machine.rs b/stackslib/src/net/download/nakamoto/download_state_machine.rs index 4c509ed5c1..f0eecaeb0b 100644 --- a/stackslib/src/net/download/nakamoto/download_state_machine.rs +++ b/stackslib/src/net/download/nakamoto/download_state_machine.rs @@ -1402,8 +1402,7 @@ impl NakamotoDownloadStateMachine { let tenure_blocks = coalesced_blocks .into_iter() .map(|(consensus_hash, block_map)| { - let mut block_list: Vec<_> = - block_map.into_iter().map(|(_, block)| block).collect(); + let mut block_list: Vec<_> = block_map.into_values().collect(); block_list.sort_unstable_by_key(|blk| blk.header.chain_length); (consensus_hash, block_list) }) diff --git a/stackslib/src/net/inv/nakamoto.rs b/stackslib/src/net/inv/nakamoto.rs index c103f16eb7..c30ef23893 100644 --- a/stackslib/src/net/inv/nakamoto.rs +++ b/stackslib/src/net/inv/nakamoto.rs @@ -750,8 +750,8 @@ impl NakamotoInvStateMachine { /// Highest reward cycle learned pub fn highest_reward_cycle(&self) -> u64 { self.inventories - .iter() - .map(|(_, inv)| inv.highest_reward_cycle()) + .values() + .map(|inv| inv.highest_reward_cycle()) .max() .unwrap_or(0) } diff --git a/stackslib/src/net/mod.rs b/stackslib/src/net/mod.rs index 415f74c739..d865722601 100644 --- a/stackslib/src/net/mod.rs +++ b/stackslib/src/net/mod.rs @@ -1580,8 +1580,8 @@ impl NetworkResult { let pushed_blocks: HashSet<_> = self .pushed_blocks - .iter() - .map(|(_, block_list)| { + .values() + .map(|block_list| { block_list .iter() .map(|block_data| { @@ -1626,8 +1626,8 @@ impl NetworkResult { let pushed_microblocks: HashSet<_> = self .pushed_microblocks - .iter() - .map(|(_, mblock_list)| { + .values() + .map(|mblock_list| { mblock_list .iter() .map(|(_, mblock_data)| { @@ -1657,14 +1657,14 @@ impl NetworkResult { fn all_nakamoto_block_ids(&self) -> HashSet { let mut naka_block_ids: HashSet<_> = self .nakamoto_blocks - .iter() - .map(|(_, nblk)| nblk.block_id()) + .values() + .map(|nblk| nblk.block_id()) .collect(); let pushed_nakamoto_blocks: HashSet<_> = self .pushed_nakamoto_blocks - .iter() - .map(|(_, naka_blocks_list)| { + .values() + .map(|naka_blocks_list| { naka_blocks_list .iter() .map(|(_, naka_blocks)| { @@ -1705,8 +1705,8 @@ impl NetworkResult { .collect(); let pushed_txids: HashSet<_> = self .pushed_transactions - .iter() - .map(|(_, tx_list)| { + .values() + .map(|tx_list| { tx_list .iter() .map(|(_, tx)| tx.txid()) @@ -1734,8 +1734,8 @@ impl NetworkResult { /// This is unique per message. fn all_msg_sigs(&self) -> HashSet { self.unhandled_messages - .iter() - .map(|(_, msgs)| { + .values() + .map(|msgs| { msgs.iter() .map(|msg| msg.preamble.signature.clone()) .collect::>() diff --git a/stackslib/src/net/relay.rs b/stackslib/src/net/relay.rs index 9121bac2c9..6ab26a93a7 100644 --- a/stackslib/src/net/relay.rs +++ b/stackslib/src/net/relay.rs @@ -2607,21 +2607,18 @@ impl Relayer { new_microblocks: Vec<(Vec, MicroblocksData)>, ) { // have the p2p thread tell our neighbors about newly-discovered blocks - let new_block_chs = new_blocks.iter().map(|(ch, _)| ch.clone()).collect(); + let new_block_chs = new_blocks.keys().cloned().collect(); let available = Relayer::load_blocks_available_data(sortdb, new_block_chs) .unwrap_or(BlocksAvailableMap::new()); if !available.is_empty() { debug!("{:?}: Blocks available: {}", &_local_peer, available.len()); if let Err(e) = self.p2p.advertize_blocks(available, new_blocks) { - warn!("Failed to advertize new blocks: {:?}", &e); + warn!("Failed to advertize new blocks: {e:?}"); } } // have the p2p thread tell our neighbors about newly-discovered confirmed microblock streams - let new_mblock_chs = new_confirmed_microblocks - .iter() - .map(|(ch, _)| ch.clone()) - .collect(); + let new_mblock_chs = new_confirmed_microblocks.keys().cloned().collect(); let mblocks_available = Relayer::load_blocks_available_data(sortdb, new_mblock_chs) .unwrap_or(BlocksAvailableMap::new()); if !mblocks_available.is_empty() { @@ -2634,7 +2631,7 @@ impl Relayer { .p2p .advertize_microblocks(mblocks_available, new_confirmed_microblocks) { - warn!("Failed to advertize new confirmed microblocks: {:?}", &e); + warn!("Failed to advertize new confirmed microblocks: {e:?}"); } } From 075125996e80dc64faa4e20268b73260af66a6c5 Mon Sep 17 00:00:00 2001 From: Jeff Bencin Date: Sat, 4 Jan 2025 23:36:11 -0500 Subject: [PATCH 03/17] chore: Apply Clippy lint `iter_with_drain` --- clarity/src/vm/tests/datamaps.rs | 8 +++---- stacks-common/src/address/c32_old.rs | 2 +- stacks-common/src/util/chunked_encoding.rs | 4 ++-- stackslib/src/net/chat.rs | 4 ++-- stackslib/src/net/connection.rs | 8 +++---- stackslib/src/net/http/request.rs | 4 ++-- stackslib/src/net/http/response.rs | 4 ++-- stackslib/src/net/server.rs | 4 ++-- stackslib/src/net/tests/download/epoch2x.rs | 23 +++++++-------------- 9 files changed, 27 insertions(+), 34 deletions(-) diff --git a/clarity/src/vm/tests/datamaps.rs b/clarity/src/vm/tests/datamaps.rs index 828de608e7..6c17766434 100644 --- a/clarity/src/vm/tests/datamaps.rs +++ b/clarity/src/vm/tests/datamaps.rs @@ -642,7 +642,7 @@ fn bad_define_maps() { "(define-map lists { name: int } contents 5)", "(define-map lists { name: int } { contents: (list 5 0 int) })", ]; - let mut expected: Vec = vec![ + let expected: Vec = vec![ CheckErrors::BadSyntaxExpectedListOfPairs.into(), CheckErrors::UnknownTypeName("contents".to_string()).into(), CheckErrors::ExpectedName.into(), @@ -650,7 +650,7 @@ fn bad_define_maps() { CheckErrors::InvalidTypeDescription.into(), ]; - for (test, expected_err) in tests.iter().zip(expected.drain(..)) { + for (test, expected_err) in tests.iter().zip(expected.into_iter()) { let outcome = execute(test).unwrap_err(); assert_eq!(outcome, expected_err); } @@ -666,7 +666,7 @@ fn bad_tuples() { "(get name five (tuple (name 1)))", "(get 1234 (tuple (name 1)))", ]; - let mut expected = vec![ + let expected = vec![ CheckErrors::NameAlreadyUsed("name".into()), CheckErrors::BadSyntaxBinding, CheckErrors::BadSyntaxBinding, @@ -678,7 +678,7 @@ fn bad_tuples() { CheckErrors::ExpectedName, ]; - for (test, expected_err) in tests.iter().zip(expected.drain(..)) { + for (test, expected_err) in tests.iter().zip(expected.into_iter()) { let outcome = execute(test).unwrap_err(); assert_eq!(outcome, expected_err.into()); } diff --git a/stacks-common/src/address/c32_old.rs b/stacks-common/src/address/c32_old.rs index 29d441e5c0..6761afac05 100644 --- a/stacks-common/src/address/c32_old.rs +++ b/stacks-common/src/address/c32_old.rs @@ -67,7 +67,7 @@ fn c32_encode(input_bytes: &[u8]) -> String { } } - let result: Vec = result.drain(..).rev().collect(); + let result: Vec = result.into_iter().rev().collect(); String::from_utf8(result).unwrap() } diff --git a/stacks-common/src/util/chunked_encoding.rs b/stacks-common/src/util/chunked_encoding.rs index 445ec5a831..d6771e2218 100644 --- a/stacks-common/src/util/chunked_encoding.rs +++ b/stacks-common/src/util/chunked_encoding.rs @@ -504,14 +504,14 @@ mod test { #[test] fn test_segment_reader() { - let mut tests = vec![ + let tests = vec![ (vec_u8(vec!["a", "b"]), "ab"), (vec_u8(vec!["aa", "bbb", "cccc"]), "aabbbcccc"), (vec_u8(vec!["aaaa", "bbb", "cc", "d", ""]), "aaaabbbccd"), (vec_u8(vec!["", "a", "", "b", ""]), "ab"), (vec_u8(vec![""]), ""), ]; - for (input_vec, expected) in tests.drain(..) { + for (input_vec, expected) in tests.into_iter() { let num_segments = input_vec.len(); let mut segment_io = SegmentReader::new(input_vec); let mut output = vec![0u8; expected.len()]; diff --git a/stackslib/src/net/chat.rs b/stackslib/src/net/chat.rs index e8deeeda47..ad73c91976 100644 --- a/stackslib/src/net/chat.rs +++ b/stackslib/src/net/chat.rs @@ -6459,7 +6459,7 @@ mod test { }]; // allowed - let mut relayers = vec![ + let relayers = vec![ RelayData { peer: NeighborAddress { addrbytes: PeerAddress([0u8; 16]), @@ -6488,7 +6488,7 @@ mod test { let relayer_map = convo.stats.take_relayers(); assert_eq!(convo.stats.relayed_messages.len(), 0); - for r in relayers.drain(..) { + for r in relayers.into_iter() { assert!(relayer_map.contains_key(&r.peer)); let stats = relayer_map.get(&r.peer).unwrap(); diff --git a/stackslib/src/net/connection.rs b/stackslib/src/net/connection.rs index 954b16ced8..deef67a835 100644 --- a/stackslib/src/net/connection.rs +++ b/stackslib/src/net/connection.rs @@ -1811,7 +1811,7 @@ mod test { test_debug!("Received {} bytes in total", total_bytes); - let mut flushed_handles = rx.recv().unwrap(); + let flushed_handles = rx.recv().unwrap(); match shared_state.lock() { Ok(ref mut conn) => { @@ -1838,15 +1838,15 @@ mod test { assert_eq!(recved.len(), 0); } Err(e) => { - assert!(false, "{:?}", &e); + assert!(false, "{e:?}"); unreachable!(); } } // got all messages let mut recved = vec![]; - for (i, rh) in flushed_handles.drain(..).enumerate() { - test_debug!("recv {}", i); + for (i, rh) in flushed_handles.into_iter().enumerate() { + test_debug!("recv {i}"); let res = rh.recv(0).unwrap(); recved.push(res); } diff --git a/stackslib/src/net/http/request.rs b/stackslib/src/net/http/request.rs index 6535f4a14a..3db81b50b3 100644 --- a/stackslib/src/net/http/request.rs +++ b/stackslib/src/net/http/request.rs @@ -117,7 +117,7 @@ impl HttpRequestPreamble { hostname: String, port: u16, keep_alive: bool, - mut keys: Vec, + keys: Vec, values: Vec, ) -> HttpRequestPreamble { assert_eq!(keys.len(), values.len()); @@ -130,7 +130,7 @@ impl HttpRequestPreamble { keep_alive, ); - for (k, v) in keys.drain(..).zip(values) { + for (k, v) in keys.into_iter().zip(values) { req.add_header(k, v); } req diff --git a/stackslib/src/net/http/response.rs b/stackslib/src/net/http/response.rs index 3ebed7e9d2..d741f7a4bf 100644 --- a/stackslib/src/net/http/response.rs +++ b/stackslib/src/net/http/response.rs @@ -259,7 +259,7 @@ impl HttpResponsePreamble { keep_alive: bool, content_length: Option, content_type: HttpContentType, - mut keys: Vec, + keys: Vec, values: Vec, ) -> HttpResponsePreamble { assert_eq!(keys.len(), values.len()); @@ -272,7 +272,7 @@ impl HttpResponsePreamble { keep_alive, ); - for (k, v) in keys.drain(..).zip(values) { + for (k, v) in keys.into_iter().zip(values) { res.add_header(k, v); } res diff --git a/stackslib/src/net/server.rs b/stackslib/src/net/server.rs index 78f0f6fbb5..dd4c8d698d 100644 --- a/stackslib/src/net/server.rs +++ b/stackslib/src/net/server.rs @@ -753,7 +753,7 @@ mod test { client_requests.push(request); } - for (i, request) in client_requests.drain(..).enumerate() { + for (i, request) in client_requests.into_iter().enumerate() { let (client_sx, client_rx) = sync_channel(1); let client = thread::spawn(move || { let mut sock = TcpStream::connect( @@ -799,7 +799,7 @@ mod test { client_handles.push(client_rx); } - for (i, client_thread) in client_threads.drain(..).enumerate() { + for (i, client_thread) in client_threads.into_iter().enumerate() { test_debug!("Client join {}", i); client_thread.join().unwrap(); let resp = client_handles[i].recv().unwrap(); diff --git a/stackslib/src/net/tests/download/epoch2x.rs b/stackslib/src/net/tests/download/epoch2x.rs index 9c995f1f32..b1d62a42b6 100644 --- a/stackslib/src/net/tests/download/epoch2x.rs +++ b/stackslib/src/net/tests/download/epoch2x.rs @@ -280,11 +280,7 @@ where make_topology(&mut peer_configs); - let mut peers = vec![]; - for conf in peer_configs.drain(..) { - let peer = TestPeer::new(conf); - peers.push(peer); - } + let mut peers: Vec<_> = peer_configs.into_iter().map(TestPeer::new).collect(); let mut num_blocks = 10; let first_stacks_block_height = { @@ -511,7 +507,7 @@ where } drop(dns_clients); - for handle in dns_threads.drain(..) { + for handle in dns_threads.into_iter() { handle.join().unwrap(); } @@ -904,7 +900,7 @@ pub fn test_get_blocks_and_microblocks_5_peers_star() { peer_configs[i].add_neighbor(&peer_0); } - for n in neighbors.drain(..) { + for n in neighbors.into_iter() { peer_configs[0].add_neighbor(&n); } }, @@ -1060,7 +1056,7 @@ pub fn test_get_blocks_and_microblocks_overwhelmed_connections() { peer_configs[i].connection_opts.max_http_clients = 1; } - for n in neighbors.drain(..) { + for n in neighbors.into_iter() { peer_configs[0].add_neighbor(&n); } }, @@ -1139,7 +1135,7 @@ pub fn test_get_blocks_and_microblocks_overwhelmed_sockets() { peer_configs[i].connection_opts.max_sockets = 10; } - for n in neighbors.drain(..) { + for n in neighbors.into_iter() { peer_configs[0].add_neighbor(&n); } }, @@ -1175,12 +1171,9 @@ pub fn test_get_blocks_and_microblocks_overwhelmed_sockets() { |peer| { // check peer health // nothing should break - match peer.network.block_downloader { - Some(ref dl) => { - assert_eq!(dl.broken_peers.len(), 0); - assert_eq!(dl.dead_peers.len(), 0); - } - None => {} + if let Some(ref dl) = peer.network.block_downloader { + assert_eq!(dl.broken_peers.len(), 0); + assert_eq!(dl.dead_peers.len(), 0); } true }, From 83f427485f2321ebe057a5b7c78efb8f4811017d Mon Sep 17 00:00:00 2001 From: Jeff Bencin Date: Sun, 5 Jan 2025 16:42:55 -0500 Subject: [PATCH 04/17] chore: Apply Clippy lint ``map_clone` --- stackslib/src/burnchains/burnchain.rs | 5 ++-- .../src/chainstate/stacks/db/unconfirmed.rs | 2 +- .../src/chainstate/stacks/index/cache.rs | 2 +- stackslib/src/clarity_cli.rs | 16 ++++++------ stackslib/src/core/mempool.rs | 2 +- stackslib/src/net/api/tests/getheaders.rs | 14 +++------- .../src/net/api/tests/postmempoolquery.rs | 2 +- stackslib/src/net/atlas/download.rs | 14 +++------- stackslib/src/net/db.rs | 3 +-- .../nakamoto/download_state_machine.rs | 2 +- stackslib/src/net/inv/nakamoto.rs | 2 +- stackslib/src/net/mod.rs | 9 +++---- stackslib/src/net/neighbors/comms.rs | 4 +-- stackslib/src/net/neighbors/db.rs | 2 +- stackslib/src/net/p2p.rs | 4 +-- stackslib/src/net/tests/inv/nakamoto.rs | 26 +++++-------------- stackslib/src/net/tests/mempool/mod.rs | 12 ++------- 17 files changed, 40 insertions(+), 81 deletions(-) diff --git a/stackslib/src/burnchains/burnchain.rs b/stackslib/src/burnchains/burnchain.rs index caeefe538c..648da211c8 100644 --- a/stackslib/src/burnchains/burnchain.rs +++ b/stackslib/src/burnchains/burnchain.rs @@ -136,7 +136,7 @@ impl BurnchainStateTransition { return Some(block_total_burns[0]); } else if block_total_burns.len() % 2 != 0 { let idx = block_total_burns.len() / 2; - return block_total_burns.get(idx).map(|b| *b); + return block_total_burns.get(idx).copied(); } else { // NOTE: the `- 1` is safe because block_total_burns.len() >= 2 let idx_left = block_total_burns.len() / 2 - 1; @@ -269,8 +269,7 @@ impl BurnchainStateTransition { let mut missed_commits_at_height = SortitionDB::get_missed_commits_by_intended(sort_tx.tx(), &sortition_id)?; if let Some(missed_commit_in_block) = missed_commits_map.remove(&sortition_id) { - missed_commits_at_height - .extend(missed_commit_in_block.into_iter().map(|x| x.clone())); + missed_commits_at_height.extend(missed_commit_in_block.into_iter().cloned()); } windowed_missed_commits.push(missed_commits_at_height); diff --git a/stackslib/src/chainstate/stacks/db/unconfirmed.rs b/stackslib/src/chainstate/stacks/db/unconfirmed.rs index b39de26c18..8973597917 100644 --- a/stackslib/src/chainstate/stacks/db/unconfirmed.rs +++ b/stackslib/src/chainstate/stacks/db/unconfirmed.rs @@ -443,7 +443,7 @@ impl UnconfirmedState { &self, txid: &Txid, ) -> Option<(StacksTransaction, BlockHeaderHash, u16)> { - self.mined_txs.get(txid).map(|x| x.clone()) + self.mined_txs.get(txid).cloned() } pub fn num_microblocks(&self) -> u64 { diff --git a/stackslib/src/chainstate/stacks/index/cache.rs b/stackslib/src/chainstate/stacks/index/cache.rs index 7547fd6d80..6ba2c5feac 100644 --- a/stackslib/src/chainstate/stacks/index/cache.rs +++ b/stackslib/src/chainstate/stacks/index/cache.rs @@ -151,7 +151,7 @@ impl TrieCacheState { /// Get the block ID, given its hash pub fn load_block_id(&self, block_hash: &T) -> Option { - self.block_id_cache.get(block_hash).map(|id| *id) + self.block_id_cache.get(block_hash).copied() } } diff --git a/stackslib/src/clarity_cli.rs b/stackslib/src/clarity_cli.rs index d07399a027..c6bc797b8d 100644 --- a/stackslib/src/clarity_cli.rs +++ b/stackslib/src/clarity_cli.rs @@ -1002,7 +1002,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().map(|x| x.clone()).collect(); + let mut argv: Vec = args.into_iter().cloned().collect(); let mainnet = if let Ok(Some(_)) = consume_arg(&mut argv, &["--testnet"], false) { false @@ -1127,7 +1127,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option = args.into_iter().map(|x| x.clone()).collect(); + let mut argv: Vec = args.into_iter().cloned().collect(); let contract_id = if let Ok(optarg) = consume_arg(&mut argv, &["--contract_id"], true) { optarg .map(|optarg_str| { @@ -1253,7 +1253,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().map(|x| x.clone()).collect(); + let mut argv: Vec = args.into_iter().cloned().collect(); let mainnet = if let Ok(Some(_)) = consume_arg(&mut argv, &["--testnet"], false) { false } else { @@ -1385,7 +1385,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().map(|x| x.clone()).collect(); + let mut argv: Vec = args.into_iter().cloned().collect(); let costs = if let Ok(Some(_)) = consume_arg(&mut argv, &["--costs"], false) { true @@ -1448,7 +1448,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().map(|x| x.clone()).collect(); + let mut argv: Vec = args.into_iter().cloned().collect(); let costs = if let Ok(Some(_)) = consume_arg(&mut argv, &["--costs"], false) { true @@ -1530,7 +1530,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().map(|x| x.clone()).collect(); + let mut argv: Vec = args.into_iter().cloned().collect(); let costs = if let Ok(Some(_)) = consume_arg(&mut argv, &["--costs"], false) { true @@ -1612,7 +1612,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().map(|x| x.clone()).collect(); + let mut argv: Vec = args.into_iter().cloned().collect(); let coverage_folder = if let Ok(covarg) = consume_arg(&mut argv, &["--c"], true) { covarg } else { @@ -1767,7 +1767,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().map(|x| x.clone()).collect(); + let mut argv: Vec = args.into_iter().cloned().collect(); let coverage_folder = if let Ok(covarg) = consume_arg(&mut argv, &["--c"], true) { covarg } else { diff --git a/stackslib/src/core/mempool.rs b/stackslib/src/core/mempool.rs index 865f99d3b0..24a59664fc 100644 --- a/stackslib/src/core/mempool.rs +++ b/stackslib/src/core/mempool.rs @@ -520,7 +520,7 @@ impl MemPoolWalkTxTypes { } pub fn only(selected: &[MemPoolWalkTxTypes]) -> HashSet { - selected.iter().map(|x| x.clone()).collect() + selected.iter().copied().collect() } } diff --git a/stackslib/src/net/api/tests/getheaders.rs b/stackslib/src/net/api/tests/getheaders.rs index 4ea4480082..f6053c5482 100644 --- a/stackslib/src/net/api/tests/getheaders.rs +++ b/stackslib/src/net/api/tests/getheaders.rs @@ -295,11 +295,8 @@ fn test_stream_getheaders() { let block_expected_headers: Vec = blocks.iter().rev().map(|blk| blk.header.clone()).collect(); - let block_expected_index_hashes: Vec = blocks_index_hashes - .iter() - .rev() - .map(|idx| idx.clone()) - .collect(); + let block_expected_index_hashes: Vec = + blocks_index_hashes.iter().rev().copied().collect(); let block_fork_expected_headers: Vec = blocks_fork .iter() @@ -307,11 +304,8 @@ fn test_stream_getheaders() { .map(|blk| blk.header.clone()) .collect(); - let block_fork_expected_index_hashes: Vec = blocks_fork_index_hashes - .iter() - .rev() - .map(|idx| idx.clone()) - .collect(); + let block_fork_expected_index_hashes: Vec = + blocks_fork_index_hashes.iter().rev().copied().collect(); // get them all -- ask for more than there is let mut stream = diff --git a/stackslib/src/net/api/tests/postmempoolquery.rs b/stackslib/src/net/api/tests/postmempoolquery.rs index 8f921525a3..55a763884e 100644 --- a/stackslib/src/net/api/tests/postmempoolquery.rs +++ b/stackslib/src/net/api/tests/postmempoolquery.rs @@ -96,7 +96,7 @@ fn test_try_make_response() { let test_rpc = TestRPC::setup(function_name!()); let mempool_txids = test_rpc.mempool_txids.clone(); - let mempool_txids: HashSet<_> = mempool_txids.iter().map(|txid| txid.clone()).collect(); + let mempool_txids: HashSet<_> = mempool_txids.iter().copied().collect(); let sync_data = test_rpc .peer_1 diff --git a/stackslib/src/net/atlas/download.rs b/stackslib/src/net/atlas/download.rs index 07e9a6cbd4..ca1b70ac7c 100644 --- a/stackslib/src/net/atlas/download.rs +++ b/stackslib/src/net/atlas/download.rs @@ -373,7 +373,7 @@ impl AttachmentsBatchStateContext { } pub fn get_peers_urls(&self) -> Vec { - self.peers.keys().map(|e| e.clone()).collect() + self.peers.keys().cloned().collect() } pub fn get_prioritized_attachments_inventory_requests( @@ -531,11 +531,7 @@ impl AttachmentsBatchStateContext { report.bump_failed_requests(); } } - let mut events_ids = results - .faulty_peers - .keys() - .map(|k| *k) - .collect::>(); + let mut events_ids = results.faulty_peers.keys().copied().collect::>(); self.events_to_deregister.append(&mut events_ids); self @@ -565,11 +561,7 @@ impl AttachmentsBatchStateContext { report.bump_failed_requests(); } } - let mut events_ids = results - .faulty_peers - .keys() - .map(|k| *k) - .collect::>(); + let mut events_ids = results.faulty_peers.keys().copied().collect::>(); self.events_to_deregister.append(&mut events_ids); self diff --git a/stackslib/src/net/db.rs b/stackslib/src/net/db.rs index 35471183f3..1cf077b2ef 100644 --- a/stackslib/src/net/db.rs +++ b/stackslib/src/net/db.rs @@ -1447,8 +1447,7 @@ impl PeerDB { let cur_dbs_set: HashSet<_> = PeerDB::static_get_peer_stacker_dbs(tx, neighbor)? .into_iter() .collect(); - let new_dbs_set: HashSet = - dbs.iter().map(|cid| cid.clone()).collect(); + let new_dbs_set: HashSet = dbs.iter().cloned().collect(); let to_insert: Vec<_> = new_dbs_set.difference(&cur_dbs_set).collect(); let to_delete: Vec<_> = cur_dbs_set.difference(&new_dbs_set).collect(); diff --git a/stackslib/src/net/download/nakamoto/download_state_machine.rs b/stackslib/src/net/download/nakamoto/download_state_machine.rs index f0eecaeb0b..b022ec2fb7 100644 --- a/stackslib/src/net/download/nakamoto/download_state_machine.rs +++ b/stackslib/src/net/download/nakamoto/download_state_machine.rs @@ -1144,7 +1144,7 @@ impl NakamotoDownloadStateMachine { ) { debug!("Run unconfirmed tenure downloaders"); - let addrs: Vec<_> = downloaders.keys().map(|addr| addr.clone()).collect(); + let addrs: Vec<_> = downloaders.keys().cloned().collect(); let mut finished = vec![]; let mut unconfirmed_blocks = HashMap::new(); let mut highest_completed_tenure_downloaders = HashMap::new(); diff --git a/stackslib/src/net/inv/nakamoto.rs b/stackslib/src/net/inv/nakamoto.rs index c30ef23893..a3b8d3a833 100644 --- a/stackslib/src/net/inv/nakamoto.rs +++ b/stackslib/src/net/inv/nakamoto.rs @@ -856,7 +856,7 @@ impl NakamotoInvStateMachine { // we're updating inventories, so preserve the state we have let mut new_inventories = HashMap::new(); - let event_ids: Vec = network.iter_peer_event_ids().map(|e_id| *e_id).collect(); + let event_ids: Vec = network.iter_peer_event_ids().copied().collect(); debug!( "Send GetNakamotoInv to up to {} peers (ibd={})", diff --git a/stackslib/src/net/mod.rs b/stackslib/src/net/mod.rs index d865722601..a1b69b7c1f 100644 --- a/stackslib/src/net/mod.rs +++ b/stackslib/src/net/mod.rs @@ -2104,8 +2104,8 @@ impl NetworkResult { self.pushed_transactions .values() .flat_map(|pushed_txs| pushed_txs.iter().map(|(_, tx)| tx.clone())) - .chain(self.uploaded_transactions.iter().map(|x| x.clone())) - .chain(self.synced_transactions.iter().map(|x| x.clone())) + .chain(self.uploaded_transactions.iter().cloned()) + .chain(self.synced_transactions.iter().cloned()) .collect() } @@ -2553,7 +2553,7 @@ pub mod test { parent: parent.clone(), winner_txid, matured_rewards: matured_rewards.to_owned(), - matured_rewards_info: matured_rewards_info.map(|info| info.clone()), + matured_rewards_info: matured_rewards_info.cloned(), reward_set_data: reward_set_data.clone(), }) } @@ -3147,8 +3147,7 @@ pub mod test { let stacker_db_syncs = Self::init_stackerdb_syncs(&test_path, &peerdb, &mut stackerdb_configs); - let stackerdb_contracts: Vec<_> = - stacker_db_syncs.keys().map(|cid| cid.clone()).collect(); + let stackerdb_contracts: Vec<_> = stacker_db_syncs.keys().cloned().collect(); let burnchain_db = config.burnchain.open_burnchain_db(false).unwrap(); diff --git a/stackslib/src/net/neighbors/comms.rs b/stackslib/src/net/neighbors/comms.rs index ed0e03f5c6..20d23061a7 100644 --- a/stackslib/src/net/neighbors/comms.rs +++ b/stackslib/src/net/neighbors/comms.rs @@ -515,9 +515,7 @@ impl NeighborComms for PeerNetworkComms { } fn get_connecting(&self, network: &PeerNetwork, nk: &NK) -> Option { - self.connecting - .get(&nk.to_neighbor_key(network)) - .map(|event_ref| *event_ref) + self.connecting.get(&nk.to_neighbor_key(network)).copied() } /// Remove a connecting neighbor because it connected diff --git a/stackslib/src/net/neighbors/db.rs b/stackslib/src/net/neighbors/db.rs index ebf83af962..595c40d54d 100644 --- a/stackslib/src/net/neighbors/db.rs +++ b/stackslib/src/net/neighbors/db.rs @@ -55,7 +55,7 @@ impl NeighborReplacements { } pub fn get_slot(&self, naddr: &NeighborAddress) -> Option { - self.replaced_neighbors.get(naddr).map(|slot| *slot) + self.replaced_neighbors.get(naddr).copied() } pub fn get_neighbor(&self, naddr: &NeighborAddress) -> Option<&Neighbor> { diff --git a/stackslib/src/net/p2p.rs b/stackslib/src/net/p2p.rs index 9300fa9150..0703c6c775 100644 --- a/stackslib/src/net/p2p.rs +++ b/stackslib/src/net/p2p.rs @@ -1861,7 +1861,7 @@ impl PeerNetwork { /// Get the event ID associated with a neighbor key pub fn get_event_id(&self, neighbor_key: &NeighborKey) -> Option { - self.events.get(neighbor_key).map(|eid| *eid) + self.events.get(neighbor_key).copied() } /// Get a ref to a conversation given a neighbor key @@ -3255,7 +3255,7 @@ impl PeerNetwork { let neighbor_keys: Vec = self .inv_state .as_ref() - .map(|inv_state| inv_state.block_stats.keys().map(|nk| nk.clone()).collect()) + .map(|inv_state| inv_state.block_stats.keys().cloned().collect()) .unwrap_or(vec![]); if self.antientropy_start_reward_cycle == 0 { diff --git a/stackslib/src/net/tests/inv/nakamoto.rs b/stackslib/src/net/tests/inv/nakamoto.rs index 3a29d453ae..992f5970b5 100644 --- a/stackslib/src/net/tests/inv/nakamoto.rs +++ b/stackslib/src/net/tests/inv/nakamoto.rs @@ -901,16 +901,9 @@ fn test_nakamoto_inv_sync_state_machine() { let _ = peer.step_with_ibd(false); let _ = other_peer.step_with_ibd(false); - let event_ids: Vec = peer - .network - .iter_peer_event_ids() - .map(|e_id| *e_id) - .collect(); - let other_event_ids: Vec = other_peer - .network - .iter_peer_event_ids() - .map(|e_id| *e_id) - .collect(); + let event_ids: Vec = peer.network.iter_peer_event_ids().copied().collect(); + let other_event_ids: Vec = + other_peer.network.iter_peer_event_ids().copied().collect(); if !event_ids.is_empty() && !other_event_ids.is_empty() { break; @@ -1032,16 +1025,9 @@ fn test_nakamoto_inv_sync_across_epoch_change() { let _ = peer.step_with_ibd(false); let _ = other_peer.step_with_ibd(false); - let event_ids: Vec = peer - .network - .iter_peer_event_ids() - .map(|e_id| *e_id) - .collect(); - let other_event_ids: Vec = other_peer - .network - .iter_peer_event_ids() - .map(|e_id| *e_id) - .collect(); + let event_ids: Vec = peer.network.iter_peer_event_ids().copied().collect(); + let other_event_ids: Vec = + other_peer.network.iter_peer_event_ids().copied().collect(); if !event_ids.is_empty() && !other_event_ids.is_empty() { break; diff --git a/stackslib/src/net/tests/mempool/mod.rs b/stackslib/src/net/tests/mempool/mod.rs index 558dddb63e..b9ee1e4e49 100644 --- a/stackslib/src/net/tests/mempool/mod.rs +++ b/stackslib/src/net/tests/mempool/mod.rs @@ -1133,16 +1133,8 @@ fn test_mempool_sync_2_peers_nakamoto_paginated() { let _ = peer_1.step_with_ibd(false); let _ = peer_2.step_with_ibd(false); - let event_ids: Vec = peer_1 - .network - .iter_peer_event_ids() - .map(|e_id| *e_id) - .collect(); - let other_event_ids: Vec = peer_2 - .network - .iter_peer_event_ids() - .map(|e_id| *e_id) - .collect(); + let event_ids: Vec = peer_1.network.iter_peer_event_ids().copied().collect(); + let other_event_ids: Vec = peer_2.network.iter_peer_event_ids().copied().collect(); if !event_ids.is_empty() && !other_event_ids.is_empty() { break; From 6dc09b1814cb8951d4c973a248ebf5de9221dd68 Mon Sep 17 00:00:00 2001 From: Jeff Bencin Date: Sun, 5 Jan 2025 16:53:10 -0500 Subject: [PATCH 05/17] chore: Apply Clippy lint ``map_entry` --- stackslib/src/chainstate/stacks/tests/chain_histories.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/stackslib/src/chainstate/stacks/tests/chain_histories.rs b/stackslib/src/chainstate/stacks/tests/chain_histories.rs index 4859451cb1..123b50a75c 100644 --- a/stackslib/src/chainstate/stacks/tests/chain_histories.rs +++ b/stackslib/src/chainstate/stacks/tests/chain_histories.rs @@ -2857,9 +2857,7 @@ pub fn mine_invalid_token_transfers_block( ); builder.force_mine_tx(clarity_tx, &tx1).unwrap(); - if !miner.spent_at_nonce.contains_key(&1) { - miner.spent_at_nonce.insert(1, 11111); - } + miner.spent_at_nonce.entry(1).or_insert(11111); let tx2 = make_token_transfer( miner, @@ -2871,9 +2869,7 @@ pub fn mine_invalid_token_transfers_block( ); builder.force_mine_tx(clarity_tx, &tx2).unwrap(); - if !miner.spent_at_nonce.contains_key(&2) { - miner.spent_at_nonce.insert(2, 22222); - } + miner.spent_at_nonce.entry(2).or_insert(22222); let tx3 = make_token_transfer( miner, From 6cb0b9e265d88caa6fe821d9b62f051589e3151e Mon Sep 17 00:00:00 2001 From: Jeff Bencin Date: Sun, 5 Jan 2025 17:24:08 -0500 Subject: [PATCH 06/17] chore(clarity): Remove unused imports and enable warning --- clarity/src/libclarity.rs | 3 +-- clarity/src/vm/analysis/analysis_db.rs | 4 ++-- .../src/vm/analysis/arithmetic_checker/mod.rs | 12 +++------- .../src/vm/analysis/read_only_checker/mod.rs | 7 ++---- .../vm/analysis/read_only_checker/tests.rs | 2 +- clarity/src/vm/analysis/tests/mod.rs | 6 +---- clarity/src/vm/analysis/trait_checker/mod.rs | 8 +------ .../src/vm/analysis/trait_checker/tests.rs | 3 +-- clarity/src/vm/analysis/type_checker/mod.rs | 14 +++-------- .../analysis/type_checker/v2_05/contexts.rs | 3 +-- .../src/vm/analysis/type_checker/v2_05/mod.rs | 13 ++++------ .../type_checker/v2_05/natives/assets.rs | 8 +++---- .../type_checker/v2_05/natives/maps.rs | 11 ++++----- .../type_checker/v2_05/natives/mod.rs | 8 ++----- .../type_checker/v2_05/natives/options.rs | 6 ++--- .../type_checker/v2_05/natives/sequences.rs | 6 ++--- .../type_checker/v2_05/tests/assets.rs | 3 --- .../type_checker/v2_05/tests/contracts.rs | 8 ++----- .../analysis/type_checker/v2_05/tests/mod.rs | 17 ++++--------- .../vm/analysis/type_checker/v2_1/contexts.rs | 5 ++-- .../src/vm/analysis/type_checker/v2_1/mod.rs | 18 +++++++------- .../type_checker/v2_1/natives/assets.rs | 11 ++++----- .../type_checker/v2_1/natives/maps.rs | 8 +++---- .../analysis/type_checker/v2_1/natives/mod.rs | 9 ++----- .../type_checker/v2_1/natives/options.rs | 9 ++----- .../type_checker/v2_1/natives/sequences.rs | 5 ++-- .../type_checker/v2_1/tests/assets.rs | 2 -- .../type_checker/v2_1/tests/contracts.rs | 8 ++----- .../analysis/type_checker/v2_1/tests/mod.rs | 16 ++++--------- clarity/src/vm/analysis/types.rs | 3 +-- clarity/src/vm/ast/definition_sorter/mod.rs | 5 ++-- clarity/src/vm/ast/definition_sorter/tests.rs | 2 +- clarity/src/vm/ast/errors.rs | 2 -- .../src/vm/ast/expression_identifier/mod.rs | 3 +-- clarity/src/vm/ast/mod.rs | 7 +++--- clarity/src/vm/ast/parser/v1.rs | 16 ++++--------- clarity/src/vm/ast/parser/v2/lexer/token.rs | 4 ---- clarity/src/vm/ast/parser/v2/mod.rs | 13 ++++------ clarity/src/vm/ast/stack_depth_checker.rs | 2 +- clarity/src/vm/ast/sugar_expander/mod.rs | 21 +++++++--------- clarity/src/vm/ast/traits_resolver/mod.rs | 16 +++++-------- clarity/src/vm/ast/types.rs | 1 - clarity/src/vm/callables.rs | 16 ++++++------- clarity/src/vm/contexts.rs | 24 +++++++------------ clarity/src/vm/contracts.rs | 6 ++--- clarity/src/vm/costs/mod.rs | 13 ++++------ clarity/src/vm/coverage.rs | 1 - clarity/src/vm/database/clarity_db.rs | 20 +++++++--------- clarity/src/vm/database/clarity_store.rs | 16 ++++--------- clarity/src/vm/database/key_value_wrapper.rs | 6 ++--- clarity/src/vm/database/mod.rs | 1 - clarity/src/vm/database/sqlite.rs | 8 ++----- clarity/src/vm/database/structures.rs | 8 ++----- clarity/src/vm/docs/contracts.rs | 2 +- clarity/src/vm/docs/mod.rs | 14 ++++------- clarity/src/vm/errors.rs | 6 ++--- clarity/src/vm/events.rs | 7 +----- clarity/src/vm/functions/arithmetic.rs | 8 +++---- clarity/src/vm/functions/assets.rs | 8 +++---- clarity/src/vm/functions/boolean.rs | 6 ++--- clarity/src/vm/functions/conversions.rs | 10 +++----- clarity/src/vm/functions/crypto.rs | 15 ++++-------- clarity/src/vm/functions/database.rs | 9 ++----- clarity/src/vm/functions/define.rs | 10 ++------ clarity/src/vm/functions/mod.rs | 15 +++--------- clarity/src/vm/functions/options.rs | 6 ++--- clarity/src/vm/functions/principals.rs | 14 +++++------ clarity/src/vm/functions/sequences.rs | 8 +++---- clarity/src/vm/functions/tuples.rs | 5 ++-- clarity/src/vm/mod.rs | 16 +++++-------- clarity/src/vm/representations.rs | 7 ++---- clarity/src/vm/test_util/mod.rs | 2 +- clarity/src/vm/tests/mod.rs | 3 +++ clarity/src/vm/tooling/mod.rs | 7 +----- clarity/src/vm/types/mod.rs | 9 +++---- clarity/src/vm/types/serialization.rs | 20 ++++------------ clarity/src/vm/types/signatures.rs | 13 ++++------ clarity/src/vm/variables.rs | 2 +- 78 files changed, 222 insertions(+), 447 deletions(-) diff --git a/clarity/src/libclarity.rs b/clarity/src/libclarity.rs index daae7dcfd7..7ce2a4f903 100644 --- a/clarity/src/libclarity.rs +++ b/clarity/src/libclarity.rs @@ -14,20 +14,19 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -#![allow(unused_imports)] #![allow(dead_code)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![cfg_attr(test, allow(unused_variables, unused_assignments))] +#[allow(unused_imports)] #[macro_use(o, slog_log, slog_trace, slog_debug, slog_info, slog_warn, slog_error)] extern crate slog; #[macro_use] extern crate serde_derive; -#[macro_use] extern crate serde_json; #[cfg(any(test, feature = "testing"))] diff --git a/clarity/src/vm/analysis/analysis_db.rs b/clarity/src/vm/analysis/analysis_db.rs index 36e1f8c970..dda74dd5c0 100644 --- a/clarity/src/vm/analysis/analysis_db.rs +++ b/clarity/src/vm/analysis/analysis_db.rs @@ -18,14 +18,14 @@ use std::collections::{BTreeMap, BTreeSet}; use stacks_common::types::StacksEpochId; -use crate::vm::analysis::errors::{CheckError, CheckErrors, CheckResult}; +use crate::vm::analysis::errors::{CheckErrors, CheckResult}; use crate::vm::analysis::type_checker::ContractAnalysis; use crate::vm::database::{ ClarityBackingStore, ClarityDeserializable, ClaritySerializable, RollbackWrapper, }; use crate::vm::representations::ClarityName; use crate::vm::types::signatures::FunctionSignature; -use crate::vm::types::{FunctionType, QualifiedContractIdentifier, TraitIdentifier, TypeSignature}; +use crate::vm::types::{FunctionType, QualifiedContractIdentifier, TraitIdentifier}; use crate::vm::ClarityVersion; pub struct AnalysisDatabase<'a> { diff --git a/clarity/src/vm/analysis/arithmetic_checker/mod.rs b/clarity/src/vm/analysis/arithmetic_checker/mod.rs index 429907b4c6..e0f774d9be 100644 --- a/clarity/src/vm/analysis/arithmetic_checker/mod.rs +++ b/clarity/src/vm/analysis/arithmetic_checker/mod.rs @@ -14,22 +14,16 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use hashbrown::HashMap; - pub use super::errors::{ check_argument_count, check_arguments_at_least, CheckError, CheckErrors, CheckResult, }; -use super::AnalysisDatabase; -use crate::vm::analysis::types::{AnalysisPass, ContractAnalysis}; +use crate::vm::analysis::types::ContractAnalysis; use crate::vm::functions::define::{DefineFunctions, DefineFunctionsParsed}; -use crate::vm::functions::{tuples, NativeFunctions}; +use crate::vm::functions::NativeFunctions; use crate::vm::representations::SymbolicExpressionType::{ Atom, AtomValue, Field, List, LiteralValue, TraitReference, }; -use crate::vm::representations::{ClarityName, SymbolicExpression, SymbolicExpressionType}; -use crate::vm::types::{ - parse_name_type_pairs, PrincipalData, TupleTypeSignature, TypeSignature, Value, -}; +use crate::vm::representations::{ClarityName, SymbolicExpression}; use crate::vm::variables::NativeVariables; use crate::vm::ClarityVersion; diff --git a/clarity/src/vm/analysis/read_only_checker/mod.rs b/clarity/src/vm/analysis/read_only_checker/mod.rs index f60ce11a44..a244bf7101 100644 --- a/clarity/src/vm/analysis/read_only_checker/mod.rs +++ b/clarity/src/vm/analysis/read_only_checker/mod.rs @@ -23,15 +23,12 @@ pub use super::errors::{ use super::AnalysisDatabase; use crate::vm::analysis::types::{AnalysisPass, ContractAnalysis}; use crate::vm::functions::define::DefineFunctionsParsed; -use crate::vm::functions::{tuples, NativeFunctions}; +use crate::vm::functions::NativeFunctions; use crate::vm::representations::SymbolicExpressionType::{ Atom, AtomValue, Field, List, LiteralValue, TraitReference, }; use crate::vm::representations::{ClarityName, SymbolicExpression, SymbolicExpressionType}; -use crate::vm::types::{ - parse_name_type_pairs, PrincipalData, TupleTypeSignature, TypeSignature, Value, -}; -use crate::vm::variables::NativeVariables; +use crate::vm::types::{PrincipalData, Value}; use crate::vm::ClarityVersion; #[cfg(test)] diff --git a/clarity/src/vm/analysis/read_only_checker/tests.rs b/clarity/src/vm/analysis/read_only_checker/tests.rs index 828e5d42bc..1f0d17117b 100644 --- a/clarity/src/vm/analysis/read_only_checker/tests.rs +++ b/clarity/src/vm/analysis/read_only_checker/tests.rs @@ -21,7 +21,7 @@ use rstest_reuse::{self, *}; use stacks_common::types::StacksEpochId; use crate::vm::analysis::type_checker::v2_1::tests::mem_type_check; -use crate::vm::analysis::{type_check, CheckError, CheckErrors}; +use crate::vm::analysis::{type_check, CheckErrors}; use crate::vm::ast::parse; use crate::vm::database::MemoryBackingStore; use crate::vm::tests::test_clarity_versions; diff --git a/clarity/src/vm/analysis/tests/mod.rs b/clarity/src/vm/analysis/tests/mod.rs index 2484ee86cd..01d5e98136 100644 --- a/clarity/src/vm/analysis/tests/mod.rs +++ b/clarity/src/vm/analysis/tests/mod.rs @@ -16,12 +16,8 @@ use stacks_common::types::StacksEpochId; -use crate::vm::analysis::errors::CheckErrors; +use crate::vm::analysis::mem_type_check as mem_run_analysis; use crate::vm::analysis::type_checker::v2_1::tests::mem_type_check; -use crate::vm::analysis::{ - mem_type_check as mem_run_analysis, type_check, AnalysisDatabase, ContractAnalysis, -}; -use crate::vm::ast::parse; use crate::vm::ClarityVersion; #[test] diff --git a/clarity/src/vm/analysis/trait_checker/mod.rs b/clarity/src/vm/analysis/trait_checker/mod.rs index 868c1d378e..87a31a9867 100644 --- a/clarity/src/vm/analysis/trait_checker/mod.rs +++ b/clarity/src/vm/analysis/trait_checker/mod.rs @@ -14,17 +14,11 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use hashbrown::HashMap; use stacks_common::types::StacksEpochId; -use crate::vm::analysis::errors::{CheckError, CheckErrors, CheckResult}; +use crate::vm::analysis::errors::{CheckErrors, CheckResult}; use crate::vm::analysis::types::{AnalysisPass, ContractAnalysis}; use crate::vm::analysis::AnalysisDatabase; -use crate::vm::functions::define::{DefineFunctions, DefineFunctionsParsed}; -use crate::vm::functions::NativeFunctions; -use crate::vm::representations::SymbolicExpressionType::{Atom, AtomValue, List, LiteralValue}; -use crate::vm::representations::{ClarityName, SymbolicExpression}; -use crate::vm::types::{FunctionType, TraitIdentifier, TypeSignature, Value}; pub struct TraitChecker { epoch: StacksEpochId, diff --git a/clarity/src/vm/analysis/trait_checker/tests.rs b/clarity/src/vm/analysis/trait_checker/tests.rs index b1d9bdb222..ab997afc58 100644 --- a/clarity/src/vm/analysis/trait_checker/tests.rs +++ b/clarity/src/vm/analysis/trait_checker/tests.rs @@ -20,9 +20,8 @@ use rstest::rstest; use rstest_reuse::{self, *}; use stacks_common::types::StacksEpochId; -use crate::vm::analysis::contract_interface_builder::build_contract_interface; use crate::vm::analysis::errors::CheckErrors; -use crate::vm::analysis::{type_check, AnalysisDatabase, CheckError}; +use crate::vm::analysis::{type_check, CheckError}; use crate::vm::ast::errors::ParseErrors; use crate::vm::ast::{build_ast, parse}; use crate::vm::database::MemoryBackingStore; diff --git a/clarity/src/vm/analysis/type_checker/mod.rs b/clarity/src/vm/analysis/type_checker/mod.rs index 36aa2519cc..68bbe1873e 100644 --- a/clarity/src/vm/analysis/type_checker/mod.rs +++ b/clarity/src/vm/analysis/type_checker/mod.rs @@ -20,19 +20,11 @@ pub mod v2_1; use stacks_common::types::StacksEpochId; -use super::errors::{ - check_argument_count, check_arguments_at_least, check_arguments_at_most, CheckError, - CheckErrors, CheckResult, -}; +use super::errors::{CheckErrors, CheckResult}; pub use super::types::{AnalysisPass, ContractAnalysis}; use super::AnalysisDatabase; -use crate::vm::costs::{analysis_typecheck_cost, CostTracker, LimitedCostTracker}; -use crate::vm::types::signatures::{ - CallableSubtype, FunctionArgSignature, FunctionReturnsSignature, -}; -use crate::vm::types::{ - FixedFunction, FunctionType, PrincipalData, SequenceSubtype, StringSubtype, TypeSignature, -}; +use crate::vm::costs::CostTracker; +use crate::vm::types::{FunctionType, TypeSignature}; use crate::vm::{ClarityVersion, Value}; impl FunctionType { diff --git a/clarity/src/vm/analysis/type_checker/v2_05/contexts.rs b/clarity/src/vm/analysis/type_checker/v2_05/contexts.rs index 2a11f6839f..f765878254 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/contexts.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/contexts.rs @@ -20,8 +20,7 @@ use hashbrown::{HashMap, HashSet}; use crate::vm::analysis::errors::{CheckError, CheckErrors, CheckResult}; use crate::vm::analysis::types::ContractAnalysis; -use crate::vm::contexts::MAX_CONTEXT_DEPTH; -use crate::vm::representations::{ClarityName, SymbolicExpression}; +use crate::vm::representations::ClarityName; use crate::vm::types::signatures::FunctionSignature; use crate::vm::types::{FunctionType, TraitIdentifier, TypeSignature}; diff --git a/clarity/src/vm/analysis/type_checker/v2_05/mod.rs b/clarity/src/vm/analysis/type_checker/v2_05/mod.rs index 77083b88cf..82e1e50490 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/mod.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/mod.rs @@ -20,34 +20,31 @@ pub mod natives; use std::collections::BTreeMap; -use hashbrown::HashMap; use stacks_common::types::StacksEpochId; use self::contexts::ContractContext; pub use self::natives::{SimpleNativeFunction, TypedNativeFunction}; use super::contexts::{TypeMap, TypingContext}; -use super::{AnalysisPass, ContractAnalysis}; +use super::ContractAnalysis; pub use crate::vm::analysis::errors::{ check_argument_count, check_arguments_at_least, CheckError, CheckErrors, CheckResult, }; use crate::vm::analysis::AnalysisDatabase; -use crate::vm::contexts::Environment; use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::{ - analysis_typecheck_cost, cost_functions, runtime_cost, ClarityCostFunctionReference, - CostErrors, CostOverflowingMath, CostTracker, ExecutionCost, LimitedCostTracker, + analysis_typecheck_cost, runtime_cost, CostErrors, CostOverflowingMath, CostTracker, + ExecutionCost, LimitedCostTracker, }; -use crate::vm::errors::InterpreterError; use crate::vm::functions::define::DefineFunctionsParsed; use crate::vm::functions::NativeFunctions; use crate::vm::representations::SymbolicExpressionType::{ Atom, AtomValue, Field, List, LiteralValue, TraitReference, }; use crate::vm::representations::{depth_traverse, ClarityName, SymbolicExpression}; -use crate::vm::types::signatures::{FunctionSignature, BUFF_20}; +use crate::vm::types::signatures::FunctionSignature; use crate::vm::types::{ parse_name_type_pairs, FixedFunction, FunctionArg, FunctionType, PrincipalData, - QualifiedContractIdentifier, TupleTypeSignature, TypeSignature, Value, + QualifiedContractIdentifier, TypeSignature, Value, }; use crate::vm::variables::NativeVariables; use crate::vm::ClarityVersion; diff --git a/clarity/src/vm/analysis/type_checker/v2_05/natives/assets.rs b/clarity/src/vm/analysis/type_checker/v2_05/natives/assets.rs index dfd55e2df2..ad066938ce 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/natives/assets.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/natives/assets.rs @@ -14,12 +14,12 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use super::{no_type, FunctionType, TypeChecker, TypeResult, TypingContext}; -use crate::vm::analysis::errors::{check_argument_count, CheckError, CheckErrors, CheckResult}; +use super::{TypeChecker, TypeResult, TypingContext}; +use crate::vm::analysis::errors::{check_argument_count, CheckErrors}; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost}; +use crate::vm::costs::runtime_cost; use crate::vm::representations::SymbolicExpression; -use crate::vm::types::{BlockInfoProperty, TupleTypeSignature, TypeSignature, MAX_VALUE_SIZE}; +use crate::vm::types::TypeSignature; pub fn check_special_get_owner( checker: &mut TypeChecker, diff --git a/clarity/src/vm/analysis/type_checker/v2_05/natives/maps.rs b/clarity/src/vm/analysis/type_checker/v2_05/natives/maps.rs index 497a01da2b..b8d36b2f82 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/natives/maps.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/natives/maps.rs @@ -16,16 +16,13 @@ use stacks_common::types::StacksEpochId; -use super::check_special_tuple_cons; use crate::vm::analysis::type_checker::v2_05::{ - check_arguments_at_least, no_type, CheckError, CheckErrors, TypeChecker, TypeResult, - TypingContext, + check_arguments_at_least, CheckError, CheckErrors, TypeChecker, TypeResult, TypingContext, }; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{analysis_typecheck_cost, cost_functions, runtime_cost}; -use crate::vm::functions::tuples; -use crate::vm::representations::{SymbolicExpression, SymbolicExpressionType}; -use crate::vm::types::{PrincipalData, TypeSignature, Value}; +use crate::vm::costs::{analysis_typecheck_cost, runtime_cost}; +use crate::vm::representations::SymbolicExpression; +use crate::vm::types::TypeSignature; pub fn check_special_fetch_entry( checker: &mut TypeChecker, diff --git a/clarity/src/vm/analysis/type_checker/v2_05/natives/mod.rs b/clarity/src/vm/analysis/type_checker/v2_05/natives/mod.rs index 3c5ab99029..11dbd2d04c 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/natives/mod.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/natives/mod.rs @@ -19,17 +19,13 @@ use stacks_common::types::StacksEpochId; use super::{ check_argument_count, check_arguments_at_least, no_type, TypeChecker, TypeResult, TypingContext, }; -use crate::vm::analysis::errors::{CheckError, CheckErrors, CheckResult}; +use crate::vm::analysis::errors::{CheckError, CheckErrors}; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{ - analysis_typecheck_cost, cost_functions, runtime_cost, CostOverflowingMath, -}; -use crate::vm::errors::{Error as InterpError, InterpreterError, RuntimeErrorType}; +use crate::vm::costs::{analysis_typecheck_cost, runtime_cost}; use crate::vm::functions::{handle_binding_list, NativeFunctions}; use crate::vm::types::{ BlockInfoProperty, FixedFunction, FunctionArg, FunctionSignature, FunctionType, PrincipalData, TupleTypeSignature, TypeSignature, Value, BUFF_20, BUFF_32, BUFF_33, BUFF_64, BUFF_65, - MAX_VALUE_SIZE, }; use crate::vm::{ClarityName, ClarityVersion, SymbolicExpression, SymbolicExpressionType}; diff --git a/clarity/src/vm/analysis/type_checker/v2_05/natives/options.rs b/clarity/src/vm/analysis/type_checker/v2_05/natives/options.rs index b04f38b44f..55469262df 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/natives/options.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/natives/options.rs @@ -17,11 +17,11 @@ use stacks_common::types::StacksEpochId; use crate::vm::analysis::type_checker::v2_05::{ - check_argument_count, check_arguments_at_least, no_type, CheckError, CheckErrors, TypeChecker, - TypeResult, TypingContext, + check_argument_count, check_arguments_at_least, no_type, CheckErrors, TypeChecker, TypeResult, + TypingContext, }; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{analysis_typecheck_cost, cost_functions, runtime_cost}; +use crate::vm::costs::{analysis_typecheck_cost, runtime_cost}; use crate::vm::representations::{ClarityName, SymbolicExpression}; use crate::vm::types::TypeSignature; diff --git a/clarity/src/vm/analysis/type_checker/v2_05/natives/sequences.rs b/clarity/src/vm/analysis/type_checker/v2_05/natives/sequences.rs index bed885d147..e1bdb8cbbd 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/natives/sequences.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/natives/sequences.rs @@ -18,17 +18,17 @@ use stacks_common::types::StacksEpochId; use super::{SimpleNativeFunction, TypedNativeFunction}; use crate::vm::analysis::type_checker::v2_05::{ - check_argument_count, check_arguments_at_least, no_type, CheckErrors, CheckResult, TypeChecker, + check_argument_count, check_arguments_at_least, CheckErrors, CheckResult, TypeChecker, TypeResult, TypingContext, }; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{analysis_typecheck_cost, cost_functions, runtime_cost}; +use crate::vm::costs::{analysis_typecheck_cost, runtime_cost}; use crate::vm::functions::NativeFunctions; use crate::vm::representations::{SymbolicExpression, SymbolicExpressionType}; pub use crate::vm::types::signatures::{BufferLength, ListTypeData, StringUTF8Length, BUFF_1}; use crate::vm::types::SequenceSubtype::*; use crate::vm::types::StringSubtype::*; -use crate::vm::types::{FunctionType, TypeSignature, Value, MAX_VALUE_SIZE}; +use crate::vm::types::{FunctionType, TypeSignature, Value}; use crate::vm::ClarityVersion; fn get_simple_native_or_user_define( diff --git a/clarity/src/vm/analysis/type_checker/v2_05/tests/assets.rs b/clarity/src/vm/analysis/type_checker/v2_05/tests/assets.rs index 5cfc9ab992..badfba6245 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/tests/assets.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/tests/assets.rs @@ -17,7 +17,6 @@ use stacks_common::types::StacksEpochId; use crate::vm::analysis::errors::CheckErrors; -use crate::vm::analysis::AnalysisDatabase; use crate::vm::ast::parse; use crate::vm::database::MemoryBackingStore; use crate::vm::tooling::mem_type_check; @@ -151,8 +150,6 @@ fn test_names_tokens_contracts() { #[test] fn test_bad_asset_usage() { - use crate::vm::analysis::type_check; - let bad_scripts = [ "(ft-get-balance stackoos tx-sender)", "(ft-get-balance u1234 tx-sender)", diff --git a/clarity/src/vm/analysis/type_checker/v2_05/tests/contracts.rs b/clarity/src/vm/analysis/type_checker/v2_05/tests/contracts.rs index bc005e9d30..0eec9c1d67 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/tests/contracts.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/tests/contracts.rs @@ -20,14 +20,11 @@ use {assert_json_diff, serde_json}; use crate::vm::analysis::contract_interface_builder::build_contract_interface; use crate::vm::analysis::errors::CheckErrors; -use crate::vm::analysis::{ - mem_type_check, type_check, AnalysisDatabase, CheckError, ContractAnalysis, -}; +use crate::vm::analysis::{mem_type_check, type_check}; use crate::vm::ast::parse; -use crate::vm::costs::LimitedCostTracker; use crate::vm::database::MemoryBackingStore; use crate::vm::types::QualifiedContractIdentifier; -use crate::vm::{ClarityVersion, SymbolicExpression}; +use crate::vm::ClarityVersion; const SIMPLE_TOKENS: &str = "(define-map tokens { account: principal } { balance: uint }) (define-read-only (my-get-token-balance (account principal)) @@ -603,7 +600,6 @@ fn test_same_function_name() { #[test] fn test_expects() { - use crate::vm::analysis::type_check; let okay = "(define-map tokens { id: int } { balance: int }) (define-private (my-get-token-balance) (let ((balance (unwrap! diff --git a/clarity/src/vm/analysis/type_checker/v2_05/tests/mod.rs b/clarity/src/vm/analysis/type_checker/v2_05/tests/mod.rs index 1830caf7ce..c314fa319d 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/tests/mod.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/tests/mod.rs @@ -17,20 +17,15 @@ use stacks_common::types::StacksEpochId; use crate::vm::analysis::errors::CheckErrors; -use crate::vm::analysis::type_checker::v2_05::{TypeChecker, TypeResult, TypingContext}; -use crate::vm::analysis::types::ContractAnalysis; -use crate::vm::analysis::{mem_type_check, type_check, AnalysisDatabase}; +use crate::vm::analysis::mem_type_check; +use crate::vm::analysis::type_checker::v2_05::TypeResult; +use crate::vm::ast::build_ast; use crate::vm::ast::errors::ParseErrors; -use crate::vm::ast::{build_ast, parse}; -use crate::vm::contexts::OwnedEnvironment; -use crate::vm::database::MemoryBackingStore; -use crate::vm::representations::SymbolicExpression; use crate::vm::types::SequenceSubtype::*; use crate::vm::types::StringSubtype::*; -use crate::vm::types::TypeSignature::{BoolType, IntType, PrincipalType, SequenceType, UIntType}; +use crate::vm::types::TypeSignature::{BoolType, IntType, PrincipalType, UIntType}; use crate::vm::types::{ - FixedFunction, FunctionType, PrincipalData, QualifiedContractIdentifier, TypeSignature, Value, - BUFF_32, BUFF_64, + FixedFunction, FunctionType, QualifiedContractIdentifier, TypeSignature, BUFF_32, BUFF_64, }; use crate::vm::ClarityVersion; @@ -1437,8 +1432,6 @@ fn test_response_inference() { #[test] fn test_function_arg_names() { - use crate::vm::analysis::type_check; - let functions = [ "(define-private (test (x int)) (ok 0)) (define-public (test-pub (x int)) (ok 0)) diff --git a/clarity/src/vm/analysis/type_checker/v2_1/contexts.rs b/clarity/src/vm/analysis/type_checker/v2_1/contexts.rs index d210194ea4..8ac9ee8254 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/contexts.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/contexts.rs @@ -21,9 +21,8 @@ use hashbrown::{HashMap, HashSet}; use crate::vm::analysis::errors::{CheckError, CheckErrors, CheckResult}; use crate::vm::analysis::type_checker::is_reserved_word; use crate::vm::analysis::types::ContractAnalysis; -use crate::vm::contexts::MAX_CONTEXT_DEPTH; -use crate::vm::representations::{ClarityName, SymbolicExpression}; -use crate::vm::types::signatures::{CallableSubtype, FunctionSignature}; +use crate::vm::representations::ClarityName; +use crate::vm::types::signatures::FunctionSignature; use crate::vm::types::{FunctionType, QualifiedContractIdentifier, TraitIdentifier, TypeSignature}; use crate::vm::ClarityVersion; diff --git a/clarity/src/vm/analysis/type_checker/v2_1/mod.rs b/clarity/src/vm/analysis/type_checker/v2_1/mod.rs index 7899b3e27d..17ee17f615 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/mod.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/mod.rs @@ -19,23 +19,21 @@ pub mod natives; use std::collections::BTreeMap; -use hashbrown::HashMap; use stacks_common::types::StacksEpochId; use self::contexts::ContractContext; pub use self::natives::{SimpleNativeFunction, TypedNativeFunction}; use super::contexts::{TypeMap, TypingContext}; -use super::{AnalysisPass, ContractAnalysis}; +use super::ContractAnalysis; pub use crate::vm::analysis::errors::{ check_argument_count, check_arguments_at_least, check_arguments_at_most, CheckError, CheckErrors, CheckResult, }; use crate::vm::analysis::AnalysisDatabase; -use crate::vm::contexts::Environment; use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::{ - analysis_typecheck_cost, cost_functions, runtime_cost, ClarityCostFunctionReference, - CostErrors, CostOverflowingMath, CostTracker, ExecutionCost, LimitedCostTracker, + analysis_typecheck_cost, runtime_cost, CostErrors, CostOverflowingMath, CostTracker, + ExecutionCost, LimitedCostTracker, }; use crate::vm::diagnostic::Diagnostic; use crate::vm::functions::define::DefineFunctionsParsed; @@ -45,13 +43,13 @@ use crate::vm::representations::SymbolicExpressionType::{ }; use crate::vm::representations::{depth_traverse, ClarityName, SymbolicExpression}; use crate::vm::types::signatures::{ - CallableSubtype, FunctionArgSignature, FunctionReturnsSignature, FunctionSignature, BUFF_20, + CallableSubtype, FunctionArgSignature, FunctionReturnsSignature, FunctionSignature, }; use crate::vm::types::{ - parse_name_type_pairs, CallableData, FixedFunction, FunctionArg, FunctionType, ListData, - ListTypeData, OptionalData, PrincipalData, QualifiedContractIdentifier, ResponseData, - SequenceData, SequenceSubtype, StringSubtype, TraitIdentifier, TupleData, TupleTypeSignature, - TypeSignature, Value, MAX_TYPE_DEPTH, + parse_name_type_pairs, FixedFunction, FunctionArg, FunctionType, ListData, ListTypeData, + OptionalData, PrincipalData, QualifiedContractIdentifier, ResponseData, SequenceData, + SequenceSubtype, StringSubtype, TraitIdentifier, TupleData, TupleTypeSignature, TypeSignature, + Value, MAX_TYPE_DEPTH, }; use crate::vm::variables::NativeVariables; use crate::vm::ClarityVersion; diff --git a/clarity/src/vm/analysis/type_checker/v2_1/natives/assets.rs b/clarity/src/vm/analysis/type_checker/v2_1/natives/assets.rs index d94e0fad56..f91c64e1c0 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/natives/assets.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/natives/assets.rs @@ -16,15 +16,12 @@ use stacks_common::consts::TOKEN_TRANSFER_MEMO_LENGTH; -use super::{no_type, FunctionType, TypeChecker, TypeResult, TypingContext}; -use crate::vm::analysis::errors::{check_argument_count, CheckError, CheckErrors, CheckResult}; +use super::{TypeChecker, TypeResult, TypingContext}; +use crate::vm::analysis::errors::{check_argument_count, CheckErrors}; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost}; +use crate::vm::costs::runtime_cost; use crate::vm::representations::SymbolicExpression; -use crate::vm::types::{ - BlockInfoProperty, BufferLength, SequenceSubtype, TupleTypeSignature, TypeSignature, - MAX_VALUE_SIZE, -}; +use crate::vm::types::{BufferLength, SequenceSubtype, TypeSignature}; pub fn check_special_get_owner( checker: &mut TypeChecker, diff --git a/clarity/src/vm/analysis/type_checker/v2_1/natives/maps.rs b/clarity/src/vm/analysis/type_checker/v2_1/natives/maps.rs index 7ce4cfad22..676badd14f 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/natives/maps.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/natives/maps.rs @@ -16,15 +16,13 @@ use stacks_common::types::StacksEpochId; -use super::check_special_tuple_cons; use crate::vm::analysis::type_checker::v2_1::{ check_arguments_at_least, CheckError, CheckErrors, TypeChecker, TypeResult, TypingContext, }; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{analysis_typecheck_cost, cost_functions, runtime_cost}; -use crate::vm::functions::tuples; -use crate::vm::representations::{SymbolicExpression, SymbolicExpressionType}; -use crate::vm::types::{PrincipalData, TypeSignature, Value}; +use crate::vm::costs::{analysis_typecheck_cost, runtime_cost}; +use crate::vm::representations::SymbolicExpression; +use crate::vm::types::TypeSignature; pub fn check_special_fetch_entry( checker: &mut TypeChecker, diff --git a/clarity/src/vm/analysis/type_checker/v2_1/natives/mod.rs b/clarity/src/vm/analysis/type_checker/v2_1/natives/mod.rs index 7769652d25..6b807ed1da 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/natives/mod.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/natives/mod.rs @@ -20,19 +20,14 @@ use super::{ check_argument_count, check_arguments_at_least, check_arguments_at_most, compute_typecheck_cost, no_type, TypeChecker, TypeResult, TypingContext, }; -use crate::vm::analysis::errors::{CheckError, CheckErrors, CheckResult}; +use crate::vm::analysis::errors::{CheckError, CheckErrors}; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{ - analysis_typecheck_cost, cost_functions, runtime_cost, CostErrors, CostOverflowingMath, - CostTracker, -}; -use crate::vm::errors::{Error as InterpError, RuntimeErrorType}; +use crate::vm::costs::{analysis_typecheck_cost, runtime_cost, CostErrors, CostTracker}; use crate::vm::functions::{handle_binding_list, NativeFunctions}; use crate::vm::types::signatures::{ CallableSubtype, FunctionArgSignature, FunctionReturnsSignature, SequenceSubtype, ASCII_40, UTF8_40, }; -use crate::vm::types::TypeSignature::SequenceType; use crate::vm::types::{ BlockInfoProperty, BufferLength, BurnBlockInfoProperty, FixedFunction, FunctionArg, FunctionSignature, FunctionType, PrincipalData, StacksBlockInfoProperty, TenureInfoProperty, diff --git a/clarity/src/vm/analysis/type_checker/v2_1/natives/options.rs b/clarity/src/vm/analysis/type_checker/v2_1/natives/options.rs index 772bdd32a4..0e12f802d2 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/natives/options.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/natives/options.rs @@ -17,18 +17,13 @@ use stacks_common::types::StacksEpochId; use super::{ - check_argument_count, check_arguments_at_least, no_type, CheckError, CheckErrors, TypeChecker, - TypeResult, + check_argument_count, check_arguments_at_least, no_type, CheckErrors, TypeChecker, TypeResult, }; use crate::vm::analysis::type_checker::contexts::TypingContext; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{ - analysis_typecheck_cost, cost_functions, runtime_cost, CostErrors, CostTracker, -}; +use crate::vm::costs::{analysis_typecheck_cost, runtime_cost, CostErrors, CostTracker}; use crate::vm::representations::{ClarityName, SymbolicExpression}; -use crate::vm::types::signatures::CallableSubtype; use crate::vm::types::TypeSignature; -use crate::vm::ClarityVersion; pub fn check_special_okay( checker: &mut TypeChecker, diff --git a/clarity/src/vm/analysis/type_checker/v2_1/natives/sequences.rs b/clarity/src/vm/analysis/type_checker/v2_1/natives/sequences.rs index c1b3aabb17..0207fe49d8 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/natives/sequences.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/natives/sequences.rs @@ -22,15 +22,14 @@ use crate::vm::analysis::type_checker::v2_1::{ TypeResult, TypingContext, }; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{analysis_typecheck_cost, cost_functions, runtime_cost, CostTracker}; +use crate::vm::costs::{analysis_typecheck_cost, runtime_cost, CostTracker}; use crate::vm::diagnostic::Diagnostic; use crate::vm::functions::NativeFunctions; use crate::vm::representations::{SymbolicExpression, SymbolicExpressionType}; pub use crate::vm::types::signatures::{BufferLength, ListTypeData, StringUTF8Length, BUFF_1}; use crate::vm::types::SequenceSubtype::*; use crate::vm::types::StringSubtype::*; -use crate::vm::types::{FunctionType, TypeSignature, Value, MAX_VALUE_SIZE}; -use crate::vm::ClarityVersion; +use crate::vm::types::{FunctionType, TypeSignature, Value}; fn get_simple_native_or_user_define( function_name: &str, diff --git a/clarity/src/vm/analysis/type_checker/v2_1/tests/assets.rs b/clarity/src/vm/analysis/type_checker/v2_1/tests/assets.rs index ba120575bd..ab06802f27 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/tests/assets.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/tests/assets.rs @@ -22,8 +22,6 @@ use stacks_common::types::StacksEpochId; use super::contracts::type_check; use crate::vm::analysis::errors::CheckErrors; -use crate::vm::analysis::type_checker::v2_1::tests::mem_type_check; -use crate::vm::analysis::AnalysisDatabase; use crate::vm::ast::parse; use crate::vm::database::MemoryBackingStore; use crate::vm::tests::test_clarity_versions; diff --git a/clarity/src/vm/analysis/type_checker/v2_1/tests/contracts.rs b/clarity/src/vm/analysis/type_checker/v2_1/tests/contracts.rs index b87177062c..838be9e6bb 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/tests/contracts.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/tests/contracts.rs @@ -30,13 +30,10 @@ use crate::vm::analysis::{ use crate::vm::ast::parse; use crate::vm::costs::LimitedCostTracker; use crate::vm::database::MemoryBackingStore; -use crate::vm::errors::Error; use crate::vm::tests::test_clarity_versions; use crate::vm::types::signatures::CallableSubtype; -use crate::vm::types::{ - PrincipalData, QualifiedContractIdentifier, StandardPrincipalData, TypeSignature, -}; -use crate::vm::{ClarityVersion, ContractName, SymbolicExpression}; +use crate::vm::types::{QualifiedContractIdentifier, TypeSignature}; +use crate::vm::{ClarityVersion, SymbolicExpression}; fn mem_type_check_v1(snippet: &str) -> CheckResult<(Option, ContractAnalysis)> { mem_run_analysis(snippet, ClarityVersion::Clarity1, StacksEpochId::latest()) @@ -567,7 +564,6 @@ fn test_same_function_name(#[case] version: ClarityVersion, #[case] epoch: Stack #[test] fn test_expects() { - use crate::vm::analysis::type_check; let okay = "(define-map tokens { id: int } { balance: int }) (define-private (my-get-token-balance) (let ((balance (unwrap! diff --git a/clarity/src/vm/analysis/type_checker/v2_1/tests/mod.rs b/clarity/src/vm/analysis/type_checker/v2_1/tests/mod.rs index 498b52dcb0..5ce27eabcb 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/tests/mod.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/tests/mod.rs @@ -22,24 +22,20 @@ use stacks_common::types::StacksEpochId; use super::CheckResult; use crate::vm::analysis::errors::CheckErrors; -use crate::vm::analysis::type_checker::v2_1::{TypeChecker, TypeResult, TypingContext}; -use crate::vm::analysis::type_checker::SequenceSubtype; +use crate::vm::analysis::mem_type_check as mem_run_analysis; +use crate::vm::analysis::type_checker::v2_1::TypeResult; use crate::vm::analysis::types::ContractAnalysis; -use crate::vm::analysis::{mem_type_check as mem_run_analysis, AnalysisDatabase}; +use crate::vm::ast::build_ast; use crate::vm::ast::errors::ParseErrors; -use crate::vm::ast::{build_ast, parse}; -use crate::vm::contexts::OwnedEnvironment; -use crate::vm::representations::SymbolicExpression; use crate::vm::tests::test_clarity_versions; use crate::vm::types::signatures::TypeSignature::OptionalType; use crate::vm::types::signatures::{ListTypeData, StringUTF8Length}; use crate::vm::types::SequenceSubtype::*; use crate::vm::types::StringSubtype::*; use crate::vm::types::TypeSignature::{BoolType, IntType, PrincipalType, SequenceType, UIntType}; -use crate::vm::types::Value::Sequence; use crate::vm::types::{ - BufferLength, FixedFunction, FunctionType, PrincipalData, QualifiedContractIdentifier, - TraitIdentifier, TypeSignature, Value, BUFF_1, BUFF_20, BUFF_21, BUFF_32, BUFF_64, + BufferLength, FixedFunction, FunctionType, QualifiedContractIdentifier, TraitIdentifier, + TypeSignature, BUFF_1, BUFF_20, BUFF_21, BUFF_32, BUFF_64, }; use crate::vm::{execute_v2, ClarityName, ClarityVersion}; @@ -2252,8 +2248,6 @@ fn test_response_inference(#[case] version: ClarityVersion, #[case] epoch: Stack #[test] fn test_function_arg_names() { - use crate::vm::analysis::type_check; - let functions = [ "(define-private (test (x int)) (ok 0)) (define-public (test-pub (x int)) (ok 0)) diff --git a/clarity/src/vm/analysis/types.rs b/clarity/src/vm/analysis/types.rs index 60a93f9c79..5085f2bc46 100644 --- a/clarity/src/vm/analysis/types.rs +++ b/clarity/src/vm/analysis/types.rs @@ -16,14 +16,13 @@ use std::collections::{BTreeMap, BTreeSet}; -use hashbrown::HashMap; use stacks_common::types::StacksEpochId; use crate::vm::analysis::analysis_db::AnalysisDatabase; use crate::vm::analysis::contract_interface_builder::ContractInterface; use crate::vm::analysis::errors::{CheckErrors, CheckResult}; use crate::vm::analysis::type_checker::contexts::TypeMap; -use crate::vm::costs::{CostTracker, ExecutionCost, LimitedCostTracker}; +use crate::vm::costs::LimitedCostTracker; use crate::vm::types::signatures::FunctionSignature; use crate::vm::types::{FunctionType, QualifiedContractIdentifier, TraitIdentifier, TypeSignature}; use crate::vm::{ClarityName, ClarityVersion, SymbolicExpression}; diff --git a/clarity/src/vm/ast/definition_sorter/mod.rs b/clarity/src/vm/ast/definition_sorter/mod.rs index bd611851b6..2be40271e6 100644 --- a/clarity/src/vm/ast/definition_sorter/mod.rs +++ b/clarity/src/vm/ast/definition_sorter/mod.rs @@ -17,9 +17,9 @@ use hashbrown::{HashMap, HashSet}; use crate::vm::ast::errors::{ParseError, ParseErrors, ParseResult}; -use crate::vm::ast::types::{BuildASTPass, ContractAST}; +use crate::vm::ast::types::ContractAST; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost, CostTracker, LimitedCostTracker}; +use crate::vm::costs::{runtime_cost, CostTracker}; use crate::vm::functions::define::DefineFunctions; use crate::vm::functions::NativeFunctions; use crate::vm::representations::PreSymbolicExpressionType::{ @@ -27,7 +27,6 @@ use crate::vm::representations::PreSymbolicExpressionType::{ SugaredFieldIdentifier, TraitReference, Tuple, }; use crate::vm::representations::{ClarityName, PreSymbolicExpression}; -use crate::vm::types::Value; use crate::vm::ClarityVersion; #[cfg(test)] diff --git a/clarity/src/vm/ast/definition_sorter/tests.rs b/clarity/src/vm/ast/definition_sorter/tests.rs index 2c993db266..0142052c50 100644 --- a/clarity/src/vm/ast/definition_sorter/tests.rs +++ b/clarity/src/vm/ast/definition_sorter/tests.rs @@ -24,7 +24,7 @@ use crate::vm::ast::definition_sorter::DefinitionSorter; use crate::vm::ast::errors::{ParseErrors, ParseResult}; use crate::vm::ast::expression_identifier::ExpressionIdentifier; use crate::vm::ast::parser; -use crate::vm::ast::types::{BuildASTPass, ContractAST}; +use crate::vm::ast::types::ContractAST; use crate::vm::types::QualifiedContractIdentifier; use crate::vm::ClarityVersion; diff --git a/clarity/src/vm/ast/errors.rs b/clarity/src/vm/ast/errors.rs index 56f8e40f86..6c668bacc1 100644 --- a/clarity/src/vm/ast/errors.rs +++ b/clarity/src/vm/ast/errors.rs @@ -21,7 +21,6 @@ use crate::vm::ast::parser::v2::lexer::token::Token; use crate::vm::costs::{CostErrors, ExecutionCost}; use crate::vm::diagnostic::{DiagnosableError, Diagnostic, Level}; use crate::vm::representations::{PreSymbolicExpression, Span}; -use crate::vm::types::{TupleTypeSignature, TypeSignature}; use crate::vm::MAX_CALL_STACK_DEPTH; pub type ParseResult = Result; @@ -308,7 +307,6 @@ impl DiagnosableError for ParseErrors { } fn level(&self) -> crate::vm::diagnostic::Level { - use self::ParseErrors::*; match self { ParseErrors::NoteToMatchThis(_) => Level::Note, ParseErrors::Lexer(lexerError) => lexerError.level(), diff --git a/clarity/src/vm/ast/expression_identifier/mod.rs b/clarity/src/vm/ast/expression_identifier/mod.rs index b8a39362ae..13b9aac2bd 100644 --- a/clarity/src/vm/ast/expression_identifier/mod.rs +++ b/clarity/src/vm/ast/expression_identifier/mod.rs @@ -15,8 +15,7 @@ // along with this program. If not, see . use crate::vm::ast::errors::{ParseError, ParseErrors, ParseResult}; -use crate::vm::ast::types::{BuildASTPass, ContractAST}; -use crate::vm::representations::PreSymbolicExpressionType::List; +use crate::vm::ast::types::ContractAST; use crate::vm::representations::SymbolicExpressionCommon; use crate::vm::ClarityVersion; diff --git a/clarity/src/vm/ast/mod.rs b/clarity/src/vm/ast/mod.rs index 5c615f46fa..263fc86526 100644 --- a/clarity/src/vm/ast/mod.rs +++ b/clarity/src/vm/ast/mod.rs @@ -36,10 +36,9 @@ use self::traits_resolver::TraitsResolver; use self::types::BuildASTPass; pub use self::types::ContractAST; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost, CostTracker, LimitedCostTracker}; +use crate::vm::costs::{runtime_cost, CostTracker}; use crate::vm::diagnostic::{Diagnostic, Level}; -use crate::vm::errors::{Error, RuntimeErrorType}; -use crate::vm::representations::{PreSymbolicExpression, SymbolicExpression}; +use crate::vm::representations::PreSymbolicExpression; use crate::vm::types::QualifiedContractIdentifier; use crate::vm::ClarityVersion; @@ -50,7 +49,7 @@ pub fn parse( source_code: &str, version: ClarityVersion, epoch: StacksEpochId, -) -> Result, Error> { +) -> Result, crate::vm::errors::Error> { let ast = build_ast(contract_identifier, source_code, &mut (), version, epoch)?; Ok(ast.expressions) } diff --git a/clarity/src/vm/ast/parser/v1.rs b/clarity/src/vm/ast/parser/v1.rs index 4cef2e5411..32f0b7001e 100644 --- a/clarity/src/vm/ast/parser/v1.rs +++ b/clarity/src/vm/ast/parser/v1.rs @@ -14,20 +14,16 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use std::cmp; - use lazy_static::lazy_static; use regex::{Captures, Regex}; -use stacks_common::address::c32::c32_address_decode; use stacks_common::util::hash::hex_bytes; use crate::vm::ast::errors::{ParseError, ParseErrors, ParseResult}; use crate::vm::ast::stack_depth_checker::AST_CALL_STACK_DEPTH_BUFFER; -use crate::vm::errors::{InterpreterResult as Result, RuntimeErrorType}; use crate::vm::representations::{ - ClarityName, ContractName, PreSymbolicExpression, PreSymbolicExpressionType, MAX_STRING_LEN, + ClarityName, ContractName, PreSymbolicExpression, MAX_STRING_LEN, }; -use crate::vm::types::{PrincipalData, QualifiedContractIdentifier, TraitIdentifier, Value}; +use crate::vm::types::{PrincipalData, TraitIdentifier, Value}; use crate::vm::MAX_CALL_STACK_DEPTH; pub const CONTRACT_MIN_NAME_LENGTH: usize = 1; @@ -734,12 +730,10 @@ pub fn parse_no_stack_limit(input: &str) -> ParseResult. -use crate::vm::ast::errors::{ParseError, ParseErrors, ParseResult}; +use crate::vm::ast::errors::{ParseErrors, ParseResult}; use crate::vm::ast::types::{BuildASTPass, ContractAST}; use crate::vm::representations::PreSymbolicExpression; use crate::vm::representations::PreSymbolicExpressionType::{List, Tuple}; diff --git a/clarity/src/vm/ast/sugar_expander/mod.rs b/clarity/src/vm/ast/sugar_expander/mod.rs index 670796cf4c..f844f5ec39 100644 --- a/clarity/src/vm/ast/sugar_expander/mod.rs +++ b/clarity/src/vm/ast/sugar_expander/mod.rs @@ -16,14 +16,9 @@ use hashbrown::{HashMap, HashSet}; -use crate::vm::ast::errors::{ParseError, ParseErrors, ParseResult}; +use crate::vm::ast::errors::{ParseErrors, ParseResult}; use crate::vm::ast::types::{BuildASTPass, ContractAST, PreExpressionsDrain}; -use crate::vm::functions::define::{DefineFunctions, DefineFunctionsParsed}; -use crate::vm::functions::NativeFunctions; -use crate::vm::representations::{ - ClarityName, PreSymbolicExpression, PreSymbolicExpressionType, SymbolicExpression, - SymbolicExpressionType, -}; +use crate::vm::representations::{ClarityName, PreSymbolicExpressionType, SymbolicExpression}; use crate::vm::types::{ PrincipalData, QualifiedContractIdentifier, StandardPrincipalData, TraitIdentifier, Value, }; @@ -169,14 +164,11 @@ impl SugarExpander { #[cfg(test)] mod test { - use crate::vm::ast::errors::{ParseError, ParseErrors}; use crate::vm::ast::sugar_expander::SugarExpander; use crate::vm::ast::types::ContractAST; - use crate::vm::representations::{ - ContractName, PreSymbolicExpression, Span, SymbolicExpression, - }; - use crate::vm::types::{PrincipalData, QualifiedContractIdentifier, StandardPrincipalData}; - use crate::vm::{ast, Value}; + use crate::vm::representations::{ContractName, PreSymbolicExpression, SymbolicExpression}; + use crate::vm::types::{PrincipalData, QualifiedContractIdentifier}; + use crate::vm::Value; fn make_pre_atom( x: &str, @@ -565,6 +557,9 @@ mod test { ); } + #[cfg(feature = "developer-mode")] + use crate::vm::representations::Span; + #[test] #[cfg(feature = "developer-mode")] fn test_attach_end_line_comment() { diff --git a/clarity/src/vm/ast/traits_resolver/mod.rs b/clarity/src/vm/ast/traits_resolver/mod.rs index 0bb4ba3186..d84e8cb673 100644 --- a/clarity/src/vm/ast/traits_resolver/mod.rs +++ b/clarity/src/vm/ast/traits_resolver/mod.rs @@ -14,20 +14,16 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use hashbrown::{HashMap, HashSet}; +use hashbrown::HashMap; -use crate::vm::analysis::AnalysisDatabase; use crate::vm::ast::errors::{ParseError, ParseErrors, ParseResult}; -use crate::vm::ast::types::{BuildASTPass, ContractAST, PreExpressionsDrain}; -use crate::vm::functions::define::{DefineFunctions, DefineFunctionsParsed}; -use crate::vm::functions::NativeFunctions; +use crate::vm::ast::types::{BuildASTPass, ContractAST}; +use crate::vm::functions::define::DefineFunctions; use crate::vm::representations::PreSymbolicExpressionType::{ - Atom, AtomValue, FieldIdentifier, List, SugaredFieldIdentifier, TraitReference, Tuple, + Atom, FieldIdentifier, List, SugaredFieldIdentifier, TraitReference, Tuple, }; -use crate::vm::representations::{ - ClarityName, PreSymbolicExpression, SymbolicExpression, TraitDefinition, -}; -use crate::vm::types::{QualifiedContractIdentifier, TraitIdentifier, Value}; +use crate::vm::representations::{ClarityName, PreSymbolicExpression, TraitDefinition}; +use crate::vm::types::{QualifiedContractIdentifier, TraitIdentifier}; use crate::vm::ClarityVersion; pub struct TraitsResolver {} diff --git a/clarity/src/vm/ast/types.rs b/clarity/src/vm/ast/types.rs index 2071130131..d969ed855f 100644 --- a/clarity/src/vm/ast/types.rs +++ b/clarity/src/vm/ast/types.rs @@ -20,7 +20,6 @@ use hashbrown::{HashMap, HashSet}; use crate::vm::ast::errors::ParseResult; use crate::vm::representations::{PreSymbolicExpression, SymbolicExpression, TraitDefinition}; -use crate::vm::types::signatures::FunctionSignature; use crate::vm::types::{QualifiedContractIdentifier, TraitIdentifier}; use crate::vm::{ClarityName, ClarityVersion}; diff --git a/clarity/src/vm/callables.rs b/clarity/src/vm/callables.rs index 4691025a8d..b7572f070e 100644 --- a/clarity/src/vm/callables.rs +++ b/clarity/src/vm/callables.rs @@ -26,14 +26,12 @@ use super::ClarityVersion; use crate::vm::analysis::errors::CheckErrors; use crate::vm::contexts::ContractContext; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost}; +use crate::vm::costs::runtime_cost; use crate::vm::errors::{check_argument_count, Error, InterpreterResult as Result}; -use crate::vm::representations::{ClarityName, Span, SymbolicExpression}; -use crate::vm::types::Value::UInt; +use crate::vm::representations::{ClarityName, SymbolicExpression}; use crate::vm::types::{ - CallableData, FunctionType, ListData, ListTypeData, OptionalData, PrincipalData, - QualifiedContractIdentifier, ResponseData, SequenceData, SequenceSubtype, TraitIdentifier, - TupleData, TupleTypeSignature, TypeSignature, + CallableData, ListData, ListTypeData, OptionalData, PrincipalData, ResponseData, SequenceData, + SequenceSubtype, TraitIdentifier, TupleData, TypeSignature, }; use crate::vm::{eval, Environment, LocalContext, Value}; @@ -377,7 +375,7 @@ impl DefinedFunction { } #[cfg(feature = "developer-mode")] - pub fn get_span(&self) -> Span { + pub fn get_span(&self) -> crate::vm::representations::Span { self.body.span.clone() } } @@ -512,7 +510,9 @@ fn clarity2_implicit_cast(type_sig: &TypeSignature, value: &Value) -> Result. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::fmt; use std::mem::replace; use hashbrown::{HashMap, HashSet}; use serde::Serialize; use serde_json::json; -use stacks_common::consts::CHAIN_ID_TESTNET; use stacks_common::types::chainstate::StacksBlockId; use stacks_common::types::StacksEpochId; @@ -30,10 +29,7 @@ use crate::vm::ast::{ASTRules, ContractAST}; use crate::vm::callables::{DefinedFunction, FunctionIdentifier}; use crate::vm::contracts::Contract; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{ - cost_functions, runtime_cost, ClarityCostFunctionReference, CostErrors, CostTracker, - ExecutionCost, LimitedCostTracker, -}; +use crate::vm::costs::{runtime_cost, CostErrors, CostTracker, ExecutionCost, LimitedCostTracker}; use crate::vm::database::{ ClarityDatabase, DataMapMetadata, DataVariableMetadata, FungibleTokenMetadata, NonFungibleTokenMetadata, @@ -42,11 +38,11 @@ use crate::vm::errors::{ CheckErrors, InterpreterError, InterpreterResult as Result, RuntimeErrorType, }; use crate::vm::events::*; -use crate::vm::representations::{ClarityName, ContractName, SymbolicExpression}; +use crate::vm::representations::{ClarityName, SymbolicExpression}; use crate::vm::types::signatures::FunctionSignature; use crate::vm::types::{ - AssetIdentifier, BuffData, CallableData, OptionalData, PrincipalData, - QualifiedContractIdentifier, TraitIdentifier, TypeSignature, Value, + AssetIdentifier, BuffData, CallableData, PrincipalData, QualifiedContractIdentifier, + TraitIdentifier, TypeSignature, Value, }; use crate::vm::version::ClarityVersion; use crate::vm::{ast, eval, is_reserved, stx_transfer_consolidated}; @@ -496,7 +492,7 @@ impl<'a, 'hooks> OwnedEnvironment<'a, 'hooks> { OwnedEnvironment { context: GlobalContext::new( false, - CHAIN_ID_TESTNET, + stacks_common::consts::CHAIN_ID_TESTNET, database, LimitedCostTracker::new_free(), epoch, @@ -519,7 +515,7 @@ impl<'a, 'hooks> OwnedEnvironment<'a, 'hooks> { OwnedEnvironment { context: GlobalContext::new( false, - CHAIN_ID_TESTNET, + stacks_common::consts::CHAIN_ID_TESTNET, database, LimitedCostTracker::new_free(), epoch, @@ -1974,11 +1970,9 @@ mod test { use super::*; use crate::vm::callables::DefineType; - use crate::vm::tests::{ - test_epochs, tl_env_factory, MemoryEnvironmentGenerator, TopLevelMemoryEnvironmentGenerator, - }; + use crate::vm::tests::{test_epochs, tl_env_factory, TopLevelMemoryEnvironmentGenerator}; use crate::vm::types::signatures::CallableSubtype; - use crate::vm::types::{FixedFunction, FunctionArg, FunctionType, StandardPrincipalData}; + use crate::vm::types::StandardPrincipalData; #[test] fn test_asset_map_abort() { diff --git a/clarity/src/vm/contracts.rs b/clarity/src/vm/contracts.rs index 1982665aee..17493a978f 100644 --- a/clarity/src/vm/contracts.rs +++ b/clarity/src/vm/contracts.rs @@ -17,13 +17,11 @@ use stacks_common::types::StacksEpochId; use crate::vm::ast::ContractAST; -use crate::vm::callables::CallableType; -use crate::vm::contexts::{ContractContext, Environment, GlobalContext, LocalContext}; +use crate::vm::contexts::{ContractContext, GlobalContext}; use crate::vm::errors::InterpreterResult as Result; -use crate::vm::representations::SymbolicExpression; +use crate::vm::eval_all; use crate::vm::types::{PrincipalData, QualifiedContractIdentifier}; use crate::vm::version::ClarityVersion; -use crate::vm::{apply, eval_all, Value}; #[derive(Serialize, Deserialize)] pub struct Contract { diff --git a/clarity/src/vm/costs/mod.rs b/clarity/src/vm/costs/mod.rs index a3c7fa7140..d86cd643bd 100644 --- a/clarity/src/vm/costs/mod.rs +++ b/clarity/src/vm/costs/mod.rs @@ -14,7 +14,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use std::collections::BTreeMap; use std::{cmp, fmt}; use hashbrown::HashMap; @@ -23,20 +22,18 @@ use serde::{Deserialize, Serialize}; use stacks_common::types::StacksEpochId; use crate::boot_util::boot_code_id; -use crate::vm::ast::ContractAST; -use crate::vm::contexts::{ContractContext, Environment, GlobalContext, OwnedEnvironment}; +use crate::vm::contexts::{ContractContext, GlobalContext}; use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::database::clarity_store::NullBackingStore; use crate::vm::database::ClarityDatabase; -use crate::vm::errors::{Error, InterpreterResult}; +use crate::vm::errors::InterpreterResult; use crate::vm::types::signatures::FunctionType::Fixed; -use crate::vm::types::signatures::{FunctionSignature, TupleTypeSignature}; +use crate::vm::types::signatures::TupleTypeSignature; use crate::vm::types::Value::UInt; use crate::vm::types::{ - FunctionArg, FunctionType, PrincipalData, QualifiedContractIdentifier, TupleData, - TypeSignature, NONE, + FunctionType, PrincipalData, QualifiedContractIdentifier, TupleData, TypeSignature, }; -use crate::vm::{ast, eval_all, ClarityName, SymbolicExpression, Value}; +use crate::vm::{eval_all, ClarityName, SymbolicExpression, Value}; pub mod constants; pub mod cost_functions; diff --git a/clarity/src/vm/coverage.rs b/clarity/src/vm/coverage.rs index 862c035f98..4e0d64e62b 100644 --- a/clarity/src/vm/coverage.rs +++ b/clarity/src/vm/coverage.rs @@ -3,7 +3,6 @@ use std::fs::File; use std::io::Write; use hashbrown::{HashMap, HashSet}; -use serde_json::Value as JsonValue; use super::functions::define::DefineFunctionsParsed; use super::EvalHook; diff --git a/clarity/src/vm/database/clarity_db.rs b/clarity/src/vm/database/clarity_db.rs index cbb8bcb4de..38101197f2 100644 --- a/clarity/src/vm/database/clarity_db.rs +++ b/clarity/src/vm/database/clarity_db.rs @@ -14,8 +14,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use serde_json; -use stacks_common::address::AddressHashMode; use stacks_common::consts::{ BITCOIN_REGTEST_FIRST_BLOCK_HASH, BITCOIN_REGTEST_FIRST_BLOCK_HEIGHT, BITCOIN_REGTEST_FIRST_BLOCK_TIMESTAMP, FIRST_BURNCHAIN_CONSENSUS_HASH, FIRST_STACKS_BLOCK_HASH, @@ -25,8 +23,8 @@ use stacks_common::types::chainstate::{ BlockHeaderHash, BurnchainHeaderHash, ConsensusHash, SortitionId, StacksAddress, StacksBlockId, TrieHash, VRFSeed, }; -use stacks_common::types::{Address, StacksEpoch as GenericStacksEpoch, StacksEpochId}; -use stacks_common::util::hash::{to_hex, Hash160, Sha256Sum, Sha512Trunc256Sum}; +use stacks_common::types::{StacksEpoch as GenericStacksEpoch, StacksEpochId}; +use stacks_common::util::hash::{to_hex, Hash160, Sha512Trunc256Sum}; use super::clarity_store::SpecialCaseHandler; use super::key_value_wrapper::ValueResult; @@ -35,20 +33,18 @@ use crate::vm::ast::ASTRules; use crate::vm::contracts::Contract; use crate::vm::costs::{CostOverflowingMath, ExecutionCost}; use crate::vm::database::structures::{ - ClarityDeserializable, ClaritySerializable, ContractMetadata, DataMapMetadata, - DataVariableMetadata, FungibleTokenMetadata, NonFungibleTokenMetadata, STXBalance, - STXBalanceSnapshot, SimmedBlock, + ClarityDeserializable, ClaritySerializable, DataMapMetadata, DataVariableMetadata, + FungibleTokenMetadata, NonFungibleTokenMetadata, STXBalance, STXBalanceSnapshot, }; use crate::vm::database::{ClarityBackingStore, RollbackWrapper}; use crate::vm::errors::{ - CheckErrors, Error, IncomparableError, InterpreterError, InterpreterResult as Result, - RuntimeErrorType, + CheckErrors, Error, InterpreterError, InterpreterResult as Result, RuntimeErrorType, }; use crate::vm::representations::ClarityName; -use crate::vm::types::serialization::{SerializationError, NONE_SERIALIZATION_LEN}; +use crate::vm::types::serialization::NONE_SERIALIZATION_LEN; use crate::vm::types::{ - byte_len_of_serialization, OptionalData, PrincipalData, QualifiedContractIdentifier, - SequenceData, StandardPrincipalData, TupleData, TupleTypeSignature, TypeSignature, Value, NONE, + byte_len_of_serialization, PrincipalData, QualifiedContractIdentifier, StandardPrincipalData, + TupleData, TypeSignature, Value, }; pub const STORE_CONTRACT_SRC_INTERFACE: bool = true; diff --git a/clarity/src/vm/database/clarity_store.rs b/clarity/src/vm/database/clarity_store.rs index 07d48c9504..a37669f499 100644 --- a/clarity/src/vm/database/clarity_store.rs +++ b/clarity/src/vm/database/clarity_store.rs @@ -14,26 +14,18 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use std::path::PathBuf; - #[cfg(feature = "canonical")] use rusqlite::Connection; -use stacks_common::types::chainstate::{BlockHeaderHash, StacksBlockId, TrieHash, VRFSeed}; -use stacks_common::util::hash::{hex_bytes, to_hex, Hash160, Sha512Trunc256Sum}; +use stacks_common::types::chainstate::{StacksBlockId, TrieHash}; +use stacks_common::util::hash::{hex_bytes, to_hex, Sha512Trunc256Sum}; use crate::vm::analysis::AnalysisDatabase; use crate::vm::contexts::GlobalContext; #[cfg(feature = "canonical")] -use crate::vm::database::SqliteConnection; use crate::vm::database::{ - BurnStateDB, ClarityDatabase, ClarityDeserializable, ClaritySerializable, HeadersDB, - NULL_BURN_STATE_DB, NULL_HEADER_DB, -}; -use crate::vm::errors::{ - CheckErrors, IncomparableError, InterpreterError, InterpreterResult as Result, - InterpreterResult, RuntimeErrorType, + ClarityDatabase, ClarityDeserializable, ClaritySerializable, NULL_BURN_STATE_DB, NULL_HEADER_DB, }; -use crate::vm::events::StacksTransactionEvent; +use crate::vm::errors::{InterpreterError, InterpreterResult as Result}; use crate::vm::types::{PrincipalData, QualifiedContractIdentifier}; use crate::vm::Value; diff --git a/clarity/src/vm/database/key_value_wrapper.rs b/clarity/src/vm/database/key_value_wrapper.rs index eecbe092ea..4d16d2dae6 100644 --- a/clarity/src/vm/database/key_value_wrapper.rs +++ b/clarity/src/vm/database/key_value_wrapper.rs @@ -26,10 +26,8 @@ use super::{ClarityBackingStore, ClarityDeserializable}; use crate::vm::database::clarity_store::make_contract_hash_key; use crate::vm::errors::{InterpreterError, InterpreterResult}; use crate::vm::types::serialization::SerializationError; -use crate::vm::types::{ - QualifiedContractIdentifier, SequenceData, SequenceSubtype, TupleData, TypeSignature, -}; -use crate::vm::{StacksEpoch, Value}; +use crate::vm::types::{QualifiedContractIdentifier, TypeSignature}; +use crate::vm::Value; #[cfg(feature = "rollback_value_check")] type RollbackValueCheck = String; diff --git a/clarity/src/vm/database/mod.rs b/clarity/src/vm/database/mod.rs index a9c2182806..65236cd88a 100644 --- a/clarity/src/vm/database/mod.rs +++ b/clarity/src/vm/database/mod.rs @@ -13,7 +13,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use hashbrown::HashMap; #[cfg(feature = "canonical")] pub use sqlite::MemoryBackingStore; diff --git a/clarity/src/vm/database/sqlite.rs b/clarity/src/vm/database/sqlite.rs index 7bc9a7130f..b5da5efedf 100644 --- a/clarity/src/vm/database/sqlite.rs +++ b/clarity/src/vm/database/sqlite.rs @@ -15,10 +15,7 @@ // along with this program. If not, see . use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; -use rusqlite::{ - params, Connection, Error as SqliteError, ErrorCode as SqliteErrorCode, OptionalExtension, Row, - Savepoint, -}; +use rusqlite::{params, Connection, OptionalExtension}; use stacks_common::types::chainstate::{BlockHeaderHash, StacksBlockId, TrieHash}; use stacks_common::types::sqlite::NO_PARAMS; use stacks_common::util::db::tx_busy_handler; @@ -30,10 +27,9 @@ use super::{ NULL_BURN_STATE_DB, NULL_HEADER_DB, }; use crate::vm::analysis::{AnalysisDatabase, CheckErrors}; -use crate::vm::contracts::Contract; use crate::vm::costs::ExecutionCost; use crate::vm::errors::{ - Error, IncomparableError, InterpreterError, InterpreterResult as Result, RuntimeErrorType, + IncomparableError, InterpreterError, InterpreterResult as Result, RuntimeErrorType, }; use crate::vm::types::QualifiedContractIdentifier; diff --git a/clarity/src/vm/database/structures.rs b/clarity/src/vm/database/structures.rs index b88420ff6a..215c0d10d3 100644 --- a/clarity/src/vm/database/structures.rs +++ b/clarity/src/vm/database/structures.rs @@ -22,12 +22,8 @@ use stacks_common::util::hash::{hex_bytes, to_hex}; use crate::vm::analysis::ContractAnalysis; use crate::vm::contracts::Contract; use crate::vm::database::ClarityDatabase; -use crate::vm::errors::{ - Error, IncomparableError, InterpreterError, InterpreterResult, RuntimeErrorType, -}; -use crate::vm::types::{ - OptionalData, PrincipalData, TupleTypeSignature, TypeSignature, Value, NONE, -}; +use crate::vm::errors::{Error, InterpreterError, RuntimeErrorType}; +use crate::vm::types::{PrincipalData, TypeSignature}; pub trait ClaritySerializable { fn serialize(&self) -> String; diff --git a/clarity/src/vm/docs/contracts.rs b/clarity/src/vm/docs/contracts.rs index 138203db71..70c1b3ecb2 100644 --- a/clarity/src/vm/docs/contracts.rs +++ b/clarity/src/vm/docs/contracts.rs @@ -86,7 +86,7 @@ fn doc_execute(program: &str) -> Result, vm::Error> { DOCS_GENERATION_EPOCH, ); global_context.execute(|g| { - let parsed = vm::ast::build_ast_with_rules( + let parsed = build_ast_with_rules( &contract_id, program, &mut (), diff --git a/clarity/src/vm/docs/mod.rs b/clarity/src/vm/docs/mod.rs index 5b2302a9b2..ae84344179 100644 --- a/clarity/src/vm/docs/mod.rs +++ b/clarity/src/vm/docs/mod.rs @@ -17,11 +17,9 @@ use super::types::signatures::{FunctionArgSignature, FunctionReturnsSignature}; use crate::vm::analysis::type_checker::v2_1::natives::SimpleNativeFunction; use crate::vm::analysis::type_checker::v2_1::TypedNativeFunction; -use crate::vm::costs::ExecutionCost; use crate::vm::functions::define::DefineFunctions; use crate::vm::functions::NativeFunctions; -use crate::vm::types::signatures::ASCII_40; -use crate::vm::types::{FixedFunction, FunctionType, SequenceSubtype, StringSubtype, Value}; +use crate::vm::types::{FixedFunction, FunctionType}; use crate::vm::variables::NativeVariables; use crate::vm::ClarityVersion; @@ -2741,13 +2739,12 @@ pub fn make_json_api_reference() -> String { #[cfg(test)] mod test { - use stacks_common::address::AddressHashMode; use stacks_common::consts::{CHAIN_ID_TESTNET, PEER_VERSION_EPOCH_2_1}; use stacks_common::types::chainstate::{ BlockHeaderHash, BurnchainHeaderHash, ConsensusHash, SortitionId, StacksAddress, StacksBlockId, VRFSeed, }; - use stacks_common::types::{Address, StacksEpochId}; + use stacks_common::types::StacksEpochId; use stacks_common::util::hash::hex_bytes; use super::{get_input_type_string, make_all_api_reference, make_json_api_reference}; @@ -2761,12 +2758,11 @@ mod test { use crate::vm::docs::get_output_type_string; use crate::vm::types::signatures::{FunctionArgSignature, FunctionReturnsSignature, ASCII_40}; use crate::vm::types::{ - BufferLength, FunctionType, PrincipalData, SequenceSubtype, StringSubtype, TupleData, - TypeSignature, + FunctionType, PrincipalData, QualifiedContractIdentifier, TupleData, TypeSignature, }; use crate::vm::{ - ast, eval_all, execute, ClarityVersion, ContractContext, Error, GlobalContext, - LimitedCostTracker, QualifiedContractIdentifier, StacksEpoch, Value, + ast, eval_all, execute, ClarityVersion, ContractContext, GlobalContext, LimitedCostTracker, + StacksEpoch, Value, }; struct DocHeadersDB {} diff --git a/clarity/src/vm/errors.rs b/clarity/src/vm/errors.rs index 911465d4ba..5f2b93c1e5 100644 --- a/clarity/src/vm/errors.rs +++ b/clarity/src/vm/errors.rs @@ -14,7 +14,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use std::error::Error as ErrorTrait; use std::{error, fmt}; #[cfg(feature = "canonical")] @@ -29,7 +28,7 @@ pub use crate::vm::analysis::errors::{ use crate::vm::ast::errors::ParseError; use crate::vm::contexts::StackTrace; use crate::vm::costs::CostErrors; -use crate::vm::types::{TypeSignature, Value}; +use crate::vm::types::Value; #[derive(Debug)] pub struct IncomparableError { @@ -236,7 +235,6 @@ impl From for Value { #[cfg(test)] mod test { use super::*; - use crate::vm::execute; #[test] #[cfg(feature = "developer-mode")] @@ -247,7 +245,7 @@ mod test { _native_:native_div "; - assert_eq!(format!("{}", execute(t).unwrap_err()), expected); + assert_eq!(format!("{}", crate::vm::execute(t).unwrap_err()), expected); } #[test] diff --git a/clarity/src/vm/events.rs b/clarity/src/vm/events.rs index 8acc55e73b..0a4db28713 100644 --- a/clarity/src/vm/events.rs +++ b/clarity/src/vm/events.rs @@ -15,15 +15,10 @@ // along with this program. If not, see . use serde_json::json; -use stacks_common::codec::StacksMessageCodec; -use stacks_common::types::chainstate::StacksAddress; use super::types::serialization::SerializationError; -use crate::vm::analysis::ContractAnalysis; -use crate::vm::costs::ExecutionCost; use crate::vm::types::{ - AssetIdentifier, BuffData, PrincipalData, QualifiedContractIdentifier, StandardPrincipalData, - Value, + AssetIdentifier, BuffData, PrincipalData, QualifiedContractIdentifier, Value, }; #[derive(Debug, Clone, PartialEq)] diff --git a/clarity/src/vm/functions/arithmetic.rs b/clarity/src/vm/functions/arithmetic.rs index 1d52ae4390..a04e813786 100644 --- a/clarity/src/vm/functions/arithmetic.rs +++ b/clarity/src/vm/functions/arithmetic.rs @@ -23,14 +23,12 @@ use crate::vm::costs::runtime_cost; use crate::vm::errors::{ check_argument_count, CheckErrors, InterpreterError, InterpreterResult, RuntimeErrorType, }; -use crate::vm::representations::{SymbolicExpression, SymbolicExpressionType}; -use crate::vm::types::signatures::ListTypeData; -use crate::vm::types::TypeSignature::BoolType; +use crate::vm::representations::SymbolicExpression; use crate::vm::types::{ - ASCIIData, BuffData, CharType, ListData, SequenceData, TypeSignature, UTF8Data, Value, + ASCIIData, BuffData, CharType, SequenceData, TypeSignature, UTF8Data, Value, }; use crate::vm::version::ClarityVersion; -use crate::vm::{apply, eval, lookup_function, CallableType, Environment, LocalContext}; +use crate::vm::{eval, Environment, LocalContext}; struct U128Ops(); struct I128Ops(); diff --git a/clarity/src/vm/functions/assets.rs b/clarity/src/vm/functions/assets.rs index 3dca730928..1d60bc7a75 100644 --- a/clarity/src/vm/functions/assets.rs +++ b/clarity/src/vm/functions/assets.rs @@ -17,17 +17,15 @@ use stacks_common::types::StacksEpochId; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost, CostTracker}; -use crate::vm::database::{ClarityDatabase, ClaritySerializable, STXBalance}; +use crate::vm::costs::{runtime_cost, CostTracker}; +use crate::vm::database::STXBalance; use crate::vm::errors::{ check_argument_count, CheckErrors, Error, InterpreterError, InterpreterResult as Result, RuntimeErrorType, }; -use crate::vm::functions::tuples; use crate::vm::representations::SymbolicExpression; use crate::vm::types::{ - AssetIdentifier, BlockInfoProperty, BuffData, CharType, OptionalData, PrincipalData, - SequenceData, TupleData, TypeSignature, Value, + AssetIdentifier, BuffData, PrincipalData, SequenceData, TupleData, TypeSignature, Value, }; use crate::vm::{eval, Environment, LocalContext}; diff --git a/clarity/src/vm/functions/boolean.rs b/clarity/src/vm/functions/boolean.rs index ea8fa2a2d4..08716cfe64 100644 --- a/clarity/src/vm/functions/boolean.rs +++ b/clarity/src/vm/functions/boolean.rs @@ -16,10 +16,8 @@ use crate::vm::contexts::{Environment, LocalContext}; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost}; -use crate::vm::errors::{ - check_argument_count, check_arguments_at_least, CheckErrors, InterpreterResult as Result, -}; +use crate::vm::costs::runtime_cost; +use crate::vm::errors::{check_arguments_at_least, CheckErrors, InterpreterResult as Result}; use crate::vm::eval; use crate::vm::representations::SymbolicExpression; use crate::vm::types::{TypeSignature, Value}; diff --git a/clarity/src/vm/functions/conversions.rs b/clarity/src/vm/functions/conversions.rs index 142c1308eb..29fa7df651 100644 --- a/clarity/src/vm/functions/conversions.rs +++ b/clarity/src/vm/functions/conversions.rs @@ -14,22 +14,18 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use stacks_common::codec::StacksMessageCodec; -use stacks_common::types::StacksEpochId; - use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::runtime_cost; use crate::vm::errors::{ check_argument_count, CheckErrors, InterpreterError, InterpreterResult as Result, }; use crate::vm::representations::SymbolicExpression; -use crate::vm::types::SequenceSubtype::{BufferType, StringType}; -use crate::vm::types::StringSubtype::ASCII; +use crate::vm::types::SequenceSubtype::BufferType; use crate::vm::types::TypeSignature::SequenceType; use crate::vm::types::{ - ASCIIData, BuffData, BufferLength, CharType, SequenceData, TypeSignature, UTF8Data, Value, + ASCIIData, BufferLength, CharType, SequenceData, TypeSignature, UTF8Data, Value, }; -use crate::vm::{apply, eval, lookup_function, Environment, LocalContext}; +use crate::vm::{eval, Environment, LocalContext}; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum EndianDirection { diff --git a/clarity/src/vm/functions/crypto.rs b/clarity/src/vm/functions/crypto.rs index 86d92283ca..9cc5f5ae9b 100644 --- a/clarity/src/vm/functions/crypto.rs +++ b/clarity/src/vm/functions/crypto.rs @@ -21,20 +21,15 @@ use stacks_common::types::chainstate::StacksAddress; use stacks_common::util::hash; use stacks_common::util::secp256k1::{secp256k1_recover, secp256k1_verify, Secp256k1PublicKey}; -use crate::vm::callables::{CallableType, NativeHandle}; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{ - constants as cost_constants, cost_functions, runtime_cost, CostTracker, MemoryConsumer, -}; +use crate::vm::costs::runtime_cost; use crate::vm::errors::{ - check_argument_count, check_arguments_at_least, CheckErrors, Error, InterpreterError, - InterpreterResult as Result, RuntimeErrorType, ShortReturnType, + check_argument_count, CheckErrors, InterpreterError, InterpreterResult as Result, }; -use crate::vm::representations::SymbolicExpressionType::{Atom, List}; -use crate::vm::representations::{ClarityName, SymbolicExpression, SymbolicExpressionType}; +use crate::vm::representations::SymbolicExpression; use crate::vm::types::{ - BuffData, CharType, PrincipalData, ResponseData, SequenceData, StacksAddressExtensions, - TypeSignature, Value, BUFF_32, BUFF_33, BUFF_65, + BuffData, SequenceData, StacksAddressExtensions, TypeSignature, Value, BUFF_32, BUFF_33, + BUFF_65, }; use crate::vm::{eval, ClarityVersion, Environment, LocalContext}; diff --git a/clarity/src/vm/functions/database.rs b/clarity/src/vm/functions/database.rs index 12fb1cd3da..4d0f880c65 100644 --- a/clarity/src/vm/functions/database.rs +++ b/clarity/src/vm/functions/database.rs @@ -14,25 +14,20 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use std::cmp; - use stacks_common::consts::CHAIN_ID_TESTNET; use stacks_common::types::chainstate::StacksBlockId; use stacks_common::types::StacksEpochId; use crate::vm::callables::DefineType; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{ - constants as cost_constants, cost_functions, runtime_cost, CostTracker, MemoryConsumer, -}; +use crate::vm::costs::{constants as cost_constants, runtime_cost, CostTracker, MemoryConsumer}; use crate::vm::errors::{ check_argument_count, check_arguments_at_least, CheckErrors, InterpreterError, InterpreterResult as Result, RuntimeErrorType, }; -use crate::vm::functions::tuples; use crate::vm::representations::{SymbolicExpression, SymbolicExpressionType}; use crate::vm::types::{ - BlockInfoProperty, BuffData, BurnBlockInfoProperty, OptionalData, PrincipalData, SequenceData, + BlockInfoProperty, BuffData, BurnBlockInfoProperty, PrincipalData, SequenceData, StacksBlockInfoProperty, TenureInfoProperty, TupleData, TypeSignature, Value, BUFF_32, }; use crate::vm::{eval, ClarityVersion, Environment, LocalContext}; diff --git a/clarity/src/vm/functions/define.rs b/clarity/src/vm/functions/define.rs index c9489c4320..1e11ff76e9 100644 --- a/clarity/src/vm/functions/define.rs +++ b/clarity/src/vm/functions/define.rs @@ -20,18 +20,12 @@ use crate::vm::callables::{DefineType, DefinedFunction}; use crate::vm::contexts::{ContractContext, Environment, LocalContext}; use crate::vm::errors::{ check_argument_count, check_arguments_at_least, CheckErrors, InterpreterResult as Result, - RuntimeErrorType, }; use crate::vm::eval; -use crate::vm::representations::SymbolicExpressionType::{ - Atom, AtomValue, Field, List, LiteralValue, -}; +use crate::vm::representations::SymbolicExpressionType::Field; use crate::vm::representations::{ClarityName, SymbolicExpression}; use crate::vm::types::signatures::FunctionSignature; -use crate::vm::types::{ - parse_name_type_pairs, PrincipalData, QualifiedContractIdentifier, TraitIdentifier, - TupleTypeSignature, TypeSignature, Value, -}; +use crate::vm::types::{parse_name_type_pairs, TraitIdentifier, TypeSignature, Value}; define_named_enum!(DefineFunctions { Constant("define-constant"), diff --git a/clarity/src/vm/functions/mod.rs b/clarity/src/vm/functions/mod.rs index a8971b3fa0..3eac4fb19e 100644 --- a/clarity/src/vm/functions/mod.rs +++ b/clarity/src/vm/functions/mod.rs @@ -14,27 +14,18 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use stacks_common::address::AddressHashMode; -use stacks_common::types::chainstate::StacksAddress; use stacks_common::types::StacksEpochId; -use stacks_common::util::hash; use crate::vm::callables::{cost_input_sized_vararg, CallableType, NativeHandle}; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{ - constants as cost_constants, cost_functions, runtime_cost, CostTracker, MemoryConsumer, -}; +use crate::vm::costs::{constants as cost_constants, runtime_cost, CostTracker, MemoryConsumer}; use crate::vm::errors::{ check_argument_count, check_arguments_at_least, CheckErrors, Error, - InterpreterResult as Result, RuntimeErrorType, ShortReturnType, + InterpreterResult as Result, ShortReturnType, }; pub use crate::vm::functions::assets::stx_transfer_consolidated; -use crate::vm::representations::SymbolicExpressionType::{Atom, List}; use crate::vm::representations::{ClarityName, SymbolicExpression, SymbolicExpressionType}; -use crate::vm::types::{ - BuffData, CharType, PrincipalData, ResponseData, SequenceData, TypeSignature, Value, BUFF_32, - BUFF_33, BUFF_65, -}; +use crate::vm::types::{PrincipalData, TypeSignature, Value}; use crate::vm::Value::CallableContract; use crate::vm::{eval, is_reserved, Environment, LocalContext}; diff --git a/clarity/src/vm/functions/options.rs b/clarity/src/vm/functions/options.rs index e3305395a5..edbd2d9908 100644 --- a/clarity/src/vm/functions/options.rs +++ b/clarity/src/vm/functions/options.rs @@ -16,10 +16,10 @@ use crate::vm::contexts::{Environment, LocalContext}; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost, CostTracker, MemoryConsumer}; +use crate::vm::costs::{runtime_cost, CostTracker, MemoryConsumer}; use crate::vm::errors::{ - check_argument_count, check_arguments_at_least, CheckErrors, InterpreterError, - InterpreterResult as Result, RuntimeErrorType, ShortReturnType, + check_arguments_at_least, CheckErrors, InterpreterError, InterpreterResult as Result, + RuntimeErrorType, ShortReturnType, }; use crate::vm::types::{CallableData, OptionalData, ResponseData, TypeSignature, Value}; use crate::vm::Value::CallableContract; diff --git a/clarity/src/vm/functions/principals.rs b/clarity/src/vm/functions/principals.rs index 99246019da..e34e50148e 100644 --- a/clarity/src/vm/functions/principals.rs +++ b/clarity/src/vm/functions/principals.rs @@ -2,23 +2,21 @@ use stacks_common::address::{ C32_ADDRESS_VERSION_MAINNET_MULTISIG, C32_ADDRESS_VERSION_MAINNET_SINGLESIG, C32_ADDRESS_VERSION_TESTNET_MULTISIG, C32_ADDRESS_VERSION_TESTNET_SINGLESIG, }; -use stacks_common::util::hash::hex_bytes; use crate::vm::contexts::GlobalContext; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost, CostTracker}; +use crate::vm::costs::runtime_cost; use crate::vm::errors::{ - check_argument_count, check_arguments_at_least, check_arguments_at_most, CheckErrors, Error, - InterpreterError, InterpreterResult as Result, RuntimeErrorType, + check_argument_count, check_arguments_at_least, check_arguments_at_most, CheckErrors, + InterpreterError, InterpreterResult as Result, }; use crate::vm::representations::{ - ClarityName, SymbolicExpression, CONTRACT_MAX_NAME_LENGTH, CONTRACT_MIN_NAME_LENGTH, + SymbolicExpression, CONTRACT_MAX_NAME_LENGTH, CONTRACT_MIN_NAME_LENGTH, }; use crate::vm::types::signatures::{BUFF_1, BUFF_20}; use crate::vm::types::{ - ASCIIData, BuffData, BufferLength, CharType, OptionalData, PrincipalData, - QualifiedContractIdentifier, ResponseData, SequenceData, SequenceSubtype, - StandardPrincipalData, TupleData, TypeSignature, Value, + ASCIIData, BuffData, CharType, OptionalData, PrincipalData, QualifiedContractIdentifier, + ResponseData, SequenceData, StandardPrincipalData, TupleData, TypeSignature, Value, }; use crate::vm::{eval, ContractName, Environment, LocalContext}; diff --git a/clarity/src/vm/functions/sequences.rs b/clarity/src/vm/functions/sequences.rs index 60445f9632..8bc89e7373 100644 --- a/clarity/src/vm/functions/sequences.rs +++ b/clarity/src/vm/functions/sequences.rs @@ -19,16 +19,16 @@ use std::cmp; use stacks_common::types::StacksEpochId; use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost, CostOverflowingMath}; +use crate::vm::costs::{runtime_cost, CostOverflowingMath}; use crate::vm::errors::{ check_argument_count, check_arguments_at_least, CheckErrors, InterpreterResult as Result, RuntimeErrorType, }; -use crate::vm::representations::{SymbolicExpression, SymbolicExpressionType}; +use crate::vm::representations::SymbolicExpression; use crate::vm::types::signatures::ListTypeData; use crate::vm::types::TypeSignature::BoolType; -use crate::vm::types::{CharType, ListData, SequenceData, TypeSignature, Value}; -use crate::vm::{apply, eval, lookup_function, CallableType, Environment, LocalContext}; +use crate::vm::types::{ListData, SequenceData, TypeSignature, Value}; +use crate::vm::{apply, eval, lookup_function, Environment, LocalContext}; pub fn list_cons( args: &[SymbolicExpression], diff --git a/clarity/src/vm/functions/tuples.rs b/clarity/src/vm/functions/tuples.rs index 9a509ccfbe..44519f1320 100644 --- a/clarity/src/vm/functions/tuples.rs +++ b/clarity/src/vm/functions/tuples.rs @@ -14,13 +14,12 @@ // along with this program. If not, see . use crate::vm::costs::cost_functions::ClarityCostFunction; -use crate::vm::costs::{cost_functions, runtime_cost}; +use crate::vm::costs::runtime_cost; use crate::vm::errors::{ check_argument_count, check_arguments_at_least, CheckErrors, InterpreterError, InterpreterResult as Result, }; -use crate::vm::representations::SymbolicExpressionType::List; -use crate::vm::representations::{SymbolicExpression, SymbolicExpressionType}; +use crate::vm::representations::SymbolicExpression; use crate::vm::types::{TupleData, TypeSignature, Value}; use crate::vm::{eval, Environment, LocalContext}; diff --git a/clarity/src/vm/mod.rs b/clarity/src/vm/mod.rs index 8680c06224..82c9b5a4db 100644 --- a/clarity/src/vm/mod.rs +++ b/clarity/src/vm/mod.rs @@ -59,7 +59,7 @@ use serde_json; use stacks_common::types::StacksEpochId; use self::analysis::ContractAnalysis; -use self::ast::{ASTRules, ContractAST}; +use self::ast::ContractAST; use self::costs::ExecutionCost; use self::diagnostic::Diagnostic; use crate::vm::callables::CallableType; @@ -69,8 +69,7 @@ pub use crate::vm::contexts::{ }; use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::{ - cost_functions, runtime_cost, CostOverflowingMath, CostTracker, LimitedCostTracker, - MemoryConsumer, + runtime_cost, CostOverflowingMath, CostTracker, LimitedCostTracker, MemoryConsumer, }; // publish the non-generic StacksEpoch form for use throughout module pub use crate::vm::database::clarity_db::StacksEpoch; @@ -83,9 +82,7 @@ pub use crate::vm::representations::{ ClarityName, ContractName, SymbolicExpression, SymbolicExpressionType, }; pub use crate::vm::types::Value; -use crate::vm::types::{ - PrincipalData, QualifiedContractIdentifier, TraitIdentifier, TypeSignature, -}; +use crate::vm::types::{PrincipalData, TypeSignature}; pub use crate::vm::version::ClarityVersion; pub const MAX_CALL_STACK_DEPTH: usize = 64; @@ -514,6 +511,7 @@ pub fn execute_with_parameters( ) -> Result> { use crate::vm::database::MemoryBackingStore; use crate::vm::tests::test_only_mainnet_to_chain_id; + use crate::vm::types::QualifiedContractIdentifier; let contract_id = QualifiedContractIdentifier::transient(); let mut contract_context = ContractContext::new(contract_id.clone(), clarity_version); @@ -572,14 +570,13 @@ pub fn execute_v2(program: &str) -> Result> { program, ClarityVersion::Clarity2, StacksEpochId::Epoch21, - ASTRules::PrecheckSize, + ast::ASTRules::PrecheckSize, false, ) } #[cfg(test)] mod test { - use hashbrown::HashMap; use stacks_common::consts::CHAIN_ID_TESTNET; use stacks_common::types::StacksEpochId; @@ -587,10 +584,9 @@ mod test { use crate::vm::callables::{DefineType, DefinedFunction}; use crate::vm::costs::LimitedCostTracker; use crate::vm::database::MemoryBackingStore; - use crate::vm::errors::RuntimeErrorType; use crate::vm::types::{QualifiedContractIdentifier, TypeSignature}; use crate::vm::{ - eval, execute, CallStack, ContractContext, Environment, GlobalContext, LocalContext, + eval, CallStack, ContractContext, Environment, GlobalContext, LocalContext, SymbolicExpression, Value, }; diff --git a/clarity/src/vm/representations.rs b/clarity/src/vm/representations.rs index 0f779b479f..8d92a5c86a 100644 --- a/clarity/src/vm/representations.rs +++ b/clarity/src/vm/representations.rs @@ -15,19 +15,16 @@ // along with this program. If not, see . use std::borrow::Borrow; -use std::cmp::Ordering; use std::fmt; use std::io::{Read, Write}; use std::ops::Deref; use lazy_static::lazy_static; use regex::Regex; -use stacks_common::codec::{ - read_next, read_next_at_most, write_next, Error as codec_error, StacksMessageCodec, -}; +use stacks_common::codec::{read_next, write_next, Error as codec_error, StacksMessageCodec}; use crate::vm::errors::RuntimeErrorType; -use crate::vm::types::{QualifiedContractIdentifier, TraitIdentifier, Value}; +use crate::vm::types::{TraitIdentifier, Value}; pub const CONTRACT_MIN_NAME_LENGTH: usize = 1; pub const CONTRACT_MAX_NAME_LENGTH: usize = 40; diff --git a/clarity/src/vm/test_util/mod.rs b/clarity/src/vm/test_util/mod.rs index 861c88ad0a..37a40182eb 100644 --- a/clarity/src/vm/test_util/mod.rs +++ b/clarity/src/vm/test_util/mod.rs @@ -14,7 +14,7 @@ use crate::vm::ast::ASTRules; use crate::vm::costs::ExecutionCost; use crate::vm::database::{BurnStateDB, HeadersDB}; use crate::vm::representations::SymbolicExpression; -use crate::vm::types::{PrincipalData, ResponseData, StandardPrincipalData, TupleData, Value}; +use crate::vm::types::{PrincipalData, StandardPrincipalData, TupleData, Value}; use crate::vm::{execute as vm_execute, execute_on_network as vm_execute_on_network, StacksEpoch}; pub struct UnitTestBurnStateDB { diff --git a/clarity/src/vm/tests/mod.rs b/clarity/src/vm/tests/mod.rs index cada7e973b..25d4713a35 100644 --- a/clarity/src/vm/tests/mod.rs +++ b/clarity/src/vm/tests/mod.rs @@ -13,6 +13,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . + +#![allow(unused_imports)] + use stacks_common::consts::{CHAIN_ID_MAINNET, CHAIN_ID_TESTNET}; use stacks_common::types::StacksEpochId; diff --git a/clarity/src/vm/tooling/mod.rs b/clarity/src/vm/tooling/mod.rs index 5b89145588..0713d4576f 100644 --- a/clarity/src/vm/tooling/mod.rs +++ b/clarity/src/vm/tooling/mod.rs @@ -1,13 +1,8 @@ -use std::collections::{BTreeMap, HashMap, HashSet}; - -use stacks_common::consts::CHAIN_ID_TESTNET; use stacks_common::types::StacksEpochId; use super::analysis::ContractAnalysis; -use super::contexts::GlobalContext; -use super::docs::contracts::ContractRef; use super::types::TypeSignature; -use super::{eval_all, ClarityVersion, ContractContext, Error as VmError, Value}; +use super::ClarityVersion; use crate::vm::analysis::{run_analysis, CheckResult}; use crate::vm::ast::{build_ast_with_rules, ASTRules}; use crate::vm::costs::LimitedCostTracker; diff --git a/clarity/src/vm/types/mod.rs b/clarity/src/vm/types/mod.rs index ef4b565834..e789676f5c 100644 --- a/clarity/src/vm/types/mod.rs +++ b/clarity/src/vm/types/mod.rs @@ -19,9 +19,8 @@ pub mod signatures; use std::collections::btree_map::Entry; use std::collections::BTreeMap; -use std::{char, cmp, fmt, str}; +use std::{char, fmt, str}; -use hashbrown::hash_map::OccupiedEntry; use regex::Regex; use stacks_common::address::c32; use stacks_common::types::chainstate::StacksAddress; @@ -29,11 +28,9 @@ use stacks_common::types::StacksEpochId; use stacks_common::util::hash; use crate::vm::errors::{ - CheckErrors, IncomparableError, InterpreterError, InterpreterResult as Result, RuntimeErrorType, -}; -use crate::vm::representations::{ - ClarityName, ContractName, SymbolicExpression, SymbolicExpressionType, + CheckErrors, InterpreterError, InterpreterResult as Result, RuntimeErrorType, }; +use crate::vm::representations::{ClarityName, ContractName, SymbolicExpression}; pub use crate::vm::types::signatures::{ parse_name_type_pairs, AssetIdentifier, BufferLength, FixedFunction, FunctionArg, FunctionSignature, FunctionType, ListTypeData, SequenceSubtype, StringSubtype, diff --git a/clarity/src/vm/types/serialization.rs b/clarity/src/vm/types/serialization.rs index 48030519c8..57bce8bb6c 100644 --- a/clarity/src/vm/types/serialization.rs +++ b/clarity/src/vm/types/serialization.rs @@ -15,11 +15,9 @@ // along with this program. If not, see . use std::io::{Read, Write}; -use std::{cmp, error, fmt, str}; +use std::{cmp, error, str}; -use hashbrown::HashMap; use lazy_static::lazy_static; -use serde_json::Value as JSONValue; use stacks_common::codec::{Error as codec_error, StacksMessageCodec}; use stacks_common::types::StacksEpochId; use stacks_common::util::hash::{hex_bytes, to_hex}; @@ -27,17 +25,12 @@ use stacks_common::util::retry::BoundReader; use super::{ListTypeData, TupleTypeSignature}; use crate::vm::database::{ClarityDeserializable, ClaritySerializable}; -use crate::vm::errors::{ - CheckErrors, Error as ClarityError, IncomparableError, InterpreterError, InterpreterResult, - RuntimeErrorType, -}; +use crate::vm::errors::{CheckErrors, Error as ClarityError, IncomparableError, InterpreterError}; use crate::vm::representations::{ClarityName, ContractName, MAX_STRING_LEN}; -use crate::vm::types::signatures::CallableSubtype; use crate::vm::types::{ - byte_len_of_serialization, BufferLength, CallableData, CharType, OptionalData, PrincipalData, - QualifiedContractIdentifier, ResponseData, SequenceData, SequenceSubtype, - StandardPrincipalData, StringSubtype, StringUTF8Length, TupleData, TypeSignature, Value, - BOUND_VALUE_SERIALIZATION_BYTES, MAX_TYPE_DEPTH, MAX_VALUE_SIZE, + BufferLength, CallableData, CharType, OptionalData, PrincipalData, QualifiedContractIdentifier, + SequenceData, SequenceSubtype, StandardPrincipalData, StringSubtype, TupleData, TypeSignature, + Value, BOUND_VALUE_SERIALIZATION_BYTES, MAX_TYPE_DEPTH, MAX_VALUE_SIZE, }; /// Errors that may occur in serialization or deserialization @@ -578,7 +571,6 @@ impl Value { top_expected_type: Option<&TypeSignature>, sanitize: bool, ) -> Result { - use super::PrincipalData::*; use super::Value::*; let mut stack = vec![DeserializeStackItem::TopLevel { @@ -1381,9 +1373,7 @@ pub mod tests { use super::super::*; use super::SerializationError; use crate::vm::database::{ClarityDeserializable, ClaritySerializable, RollbackWrapper}; - use crate::vm::errors::Error; use crate::vm::tests::test_clarity_versions; - use crate::vm::types::TypeSignature::{BoolType, IntType}; use crate::vm::ClarityVersion; fn buff_type(size: u32) -> TypeSignature { diff --git a/clarity/src/vm/types/signatures.rs b/clarity/src/vm/types/signatures.rs index a85c56ff3e..e76c7e034d 100644 --- a/clarity/src/vm/types/signatures.rs +++ b/clarity/src/vm/types/signatures.rs @@ -15,21 +15,18 @@ // along with this program. If not, see . use std::collections::btree_map::Entry; -use std::collections::{hash_map, BTreeMap}; -use std::hash::{Hash, Hasher}; -use std::ops::Deref; +use std::collections::BTreeMap; +use std::hash::Hash; use std::sync::Arc; use std::{cmp, fmt}; // TypeSignatures use hashbrown::HashSet; use lazy_static::lazy_static; -use stacks_common::address::c32; use stacks_common::types::StacksEpochId; -use stacks_common::util::hash; -use crate::vm::costs::{cost_functions, runtime_cost, CostOverflowingMath}; -use crate::vm::errors::{CheckErrors, Error as VMError, IncomparableError, RuntimeErrorType}; +use crate::vm::costs::{runtime_cost, CostOverflowingMath}; +use crate::vm::errors::CheckErrors; use crate::vm::representations::{ ClarityName, ContractName, SymbolicExpression, SymbolicExpressionType, TraitDefinition, CONTRACT_MAX_NAME_LENGTH, @@ -1933,7 +1930,7 @@ pub fn parse_name_type_pairs( // the form: // ((name1 type1) (name2 type2) (name3 type3) ...) // which is a list of 2-length lists of atoms. - use crate::vm::representations::SymbolicExpressionType::{Atom, List}; + use crate::vm::representations::SymbolicExpressionType::List; // step 1: parse it into a vec of symbolicexpression pairs. let as_pairs: Result> = name_type_pairs diff --git a/clarity/src/vm/variables.rs b/clarity/src/vm/variables.rs index a5947d00cd..0846e14140 100644 --- a/clarity/src/vm/variables.rs +++ b/clarity/src/vm/variables.rs @@ -21,7 +21,7 @@ use crate::vm::contexts::{Environment, LocalContext}; use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::runtime_cost; use crate::vm::errors::{InterpreterResult as Result, RuntimeErrorType}; -use crate::vm::types::{BuffData, Value}; +use crate::vm::types::Value; use crate::vm::ClarityVersion; define_versioned_named_enum_with_max!(NativeVariables(ClarityVersion) { From 820702c1a8df73f704e5feaf2336f97e740a31fd Mon Sep 17 00:00:00 2001 From: Aaron Blankstein Date: Fri, 17 Jan 2025 08:37:02 -0600 Subject: [PATCH 07/17] test: use last_commit_burn_height counter to address flakiness in miner_forking --- testnet/stacks-node/src/nakamoto_node/relayer.rs | 4 +++- testnet/stacks-node/src/run_loop/neon.rs | 8 +++++++- testnet/stacks-node/src/tests/signer/mod.rs | 3 +++ testnet/stacks-node/src/tests/signer/v0.rs | 16 ++++++++++++++-- 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/testnet/stacks-node/src/nakamoto_node/relayer.rs b/testnet/stacks-node/src/nakamoto_node/relayer.rs index 8cc1293acd..2f65973f62 100644 --- a/testnet/stacks-node/src/nakamoto_node/relayer.rs +++ b/testnet/stacks-node/src/nakamoto_node/relayer.rs @@ -1229,8 +1229,10 @@ impl RelayerThread { // update local state last_committed.set_txid(&txid); self.last_commits.insert(txid); + self.globals + .counters + .bump_naka_submitted_commits(last_committed.burn_tip.block_height); self.last_committed = Some(last_committed); - self.globals.counters.bump_naka_submitted_commits(); Ok(()) } diff --git a/testnet/stacks-node/src/run_loop/neon.rs b/testnet/stacks-node/src/run_loop/neon.rs index 4ecc84b73b..3bc12cdb04 100644 --- a/testnet/stacks-node/src/run_loop/neon.rs +++ b/testnet/stacks-node/src/run_loop/neon.rs @@ -106,6 +106,8 @@ pub struct Counters { pub naka_submitted_vrfs: RunLoopCounter, pub naka_submitted_commits: RunLoopCounter, + /// the burn block height when the last commit was submitted + pub naka_submitted_commit_last_burn_height: RunLoopCounter, pub naka_mined_blocks: RunLoopCounter, pub naka_rejected_blocks: RunLoopCounter, pub naka_proposed_blocks: RunLoopCounter, @@ -161,8 +163,12 @@ impl Counters { Counters::inc(&self.naka_submitted_vrfs); } - pub fn bump_naka_submitted_commits(&self) { + pub fn bump_naka_submitted_commits(&self, committed_height: u64) { Counters::inc(&self.naka_submitted_commits); + Counters::set( + &self.naka_submitted_commit_last_burn_height, + committed_height, + ); } pub fn bump_naka_mined_blocks(&self) { diff --git a/testnet/stacks-node/src/tests/signer/mod.rs b/testnet/stacks-node/src/tests/signer/mod.rs index ed4560c70a..9e59d73235 100644 --- a/testnet/stacks-node/src/tests/signer/mod.rs +++ b/testnet/stacks-node/src/tests/signer/mod.rs @@ -88,6 +88,7 @@ pub struct RunningNodes { pub run_loop_stopper: Arc, pub vrfs_submitted: RunLoopCounter, pub commits_submitted: RunLoopCounter, + pub last_commit_burn_height: RunLoopCounter, pub blocks_processed: RunLoopCounter, pub nakamoto_blocks_proposed: RunLoopCounter, pub nakamoto_blocks_mined: RunLoopCounter, @@ -902,6 +903,7 @@ fn setup_stx_btc_node( blocks_processed, naka_submitted_vrfs: vrfs_submitted, naka_submitted_commits: commits_submitted, + naka_submitted_commit_last_burn_height: last_commit_burn_height, naka_proposed_blocks: naka_blocks_proposed, naka_mined_blocks: naka_blocks_mined, naka_rejected_blocks: naka_blocks_rejected, @@ -936,6 +938,7 @@ fn setup_stx_btc_node( run_loop_stopper, vrfs_submitted, commits_submitted, + last_commit_burn_height, blocks_processed, nakamoto_blocks_proposed: naka_blocks_proposed, nakamoto_blocks_mined: naka_blocks_mined, diff --git a/testnet/stacks-node/src/tests/signer/v0.rs b/testnet/stacks-node/src/tests/signer/v0.rs index 190145279f..76a6ae02a7 100644 --- a/testnet/stacks-node/src/tests/signer/v0.rs +++ b/testnet/stacks-node/src/tests/signer/v0.rs @@ -1882,6 +1882,7 @@ fn miner_forking() { let Counters { naka_skip_commit_op: skip_commit_op_rl2, naka_submitted_commits: commits_submitted_rl2, + naka_submitted_commit_last_burn_height: commits_submitted_rl2_last_burn_height, .. } = run_loop_2.counters(); let _run_loop_2_thread = thread::Builder::new() @@ -1903,6 +1904,8 @@ fn miner_forking() { .expect("Timed out waiting for boostrapped node to catch up to the miner"); let commits_submitted_rl1 = signer_test.running_nodes.commits_submitted.clone(); + let commits_submitted_rl1_last_burn_height = + signer_test.running_nodes.last_commit_burn_height.clone(); let skip_commit_op_rl1 = signer_test .running_nodes .nakamoto_test_skip_commit_op @@ -1947,13 +1950,18 @@ fn miner_forking() { info!("Pausing stacks block proposal to force an empty tenure commit from RL2"); TEST_BROADCAST_STALL.lock().unwrap().replace(true); let rl1_commits_before = commits_submitted_rl1.load(Ordering::SeqCst); + let burn_height_before = get_burn_height(); info!("Unpausing commits from RL1"); skip_commit_op_rl1.set(false); info!("Waiting for commits from RL1"); wait_for(30, || { - Ok(commits_submitted_rl1.load(Ordering::SeqCst) > rl1_commits_before) + Ok( + commits_submitted_rl1.load(Ordering::SeqCst) > rl1_commits_before + && commits_submitted_rl1_last_burn_height.load(Ordering::SeqCst) + >= burn_height_before, + ) }) .expect("Timed out waiting for miner 1 to submit a commit op"); @@ -1984,13 +1992,17 @@ fn miner_forking() { "------------------------- RL2 Wins Sortition With Outdated View -------------------------" ); let rl2_commits_before = commits_submitted_rl2.load(Ordering::SeqCst); + let burn_height = get_burn_height(); info!("Unpausing commits from RL2"); skip_commit_op_rl2.set(false); info!("Waiting for commits from RL2"); wait_for(30, || { - Ok(commits_submitted_rl2.load(Ordering::SeqCst) > rl2_commits_before) + Ok( + commits_submitted_rl2.load(Ordering::SeqCst) > rl2_commits_before + && commits_submitted_rl2_last_burn_height.load(Ordering::SeqCst) >= burn_height, + ) }) .expect("Timed out waiting for miner 1 to submit a commit op"); From bbeb7d62e3cb49bcd64ca9e0c58a1a0fdb10ad50 Mon Sep 17 00:00:00 2001 From: Aaron Blankstein Date: Wed, 22 Jan 2025 12:22:55 -0600 Subject: [PATCH 08/17] test: fix flakiness in global_acceptance_depends_on_block_announcement --- testnet/stacks-node/src/tests/signer/v0.rs | 26 ++++++++++++---------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/testnet/stacks-node/src/tests/signer/v0.rs b/testnet/stacks-node/src/tests/signer/v0.rs index 8d7953aa72..7aeb845f47 100644 --- a/testnet/stacks-node/src/tests/signer/v0.rs +++ b/testnet/stacks-node/src/tests/signer/v0.rs @@ -9832,14 +9832,19 @@ fn global_acceptance_depends_on_block_announcement() { .stacks_client .get_peer_info() .expect("Failed to get peer info"); - Ok(info.stacks_tip_height > info_before.stacks_tip_height) + Ok(info.stacks_tip_height > info_before.stacks_tip_height + && info_before.stacks_tip_consensus_hash != info.stacks_tip_consensus_hash) }, ) - .unwrap(); + .expect("Stacks miner failed to produce new blocks during the newest burn block's tenure"); let info_after = signer_test .stacks_client .get_peer_info() .expect("Failed to get peer info"); + let info_after_stacks_block_id = StacksBlockId::new( + &info_after.stacks_tip_consensus_hash, + &info_after.stacks_tip, + ); let mut sister_block = None; let start_time = Instant::now(); while sister_block.is_none() && start_time.elapsed() < Duration::from_secs(45) { @@ -9849,17 +9854,14 @@ fn global_acceptance_depends_on_block_announcement() { .find_map(|chunk| { let message = SignerMessage::consensus_deserialize(&mut chunk.data.as_slice()) .expect("Failed to deserialize SignerMessage"); - match message { - SignerMessage::BlockProposal(proposal) => { - if proposal.block.header.consensus_hash - == info_after.stacks_tip_consensus_hash - { - Some(proposal.block) - } else { - None - } + if let SignerMessage::BlockProposal(proposal) = message { + if proposal.block.block_id() == info_after_stacks_block_id { + Some(proposal.block) + } else { + None } - _ => None, + } else { + None } }); } From b851d0f17d4f96a2ef232fa1799a2557048b7832 Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Wed, 22 Jan 2025 11:54:57 -0800 Subject: [PATCH 09/17] Create clippy-stacks alias to run in CI and to run locally Signed-off-by: Jacinta Ferrant --- .cargo/config.toml | 1 + .github/workflows/clippy.yml | 15 +-------------- CONTRIBUTING.md | 20 +++++++++++++++++++- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index 7f7e28a8b8..feaf5fec86 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,6 +1,7 @@ [alias] stacks-node = "run --package stacks-node --" fmt-stacks = "fmt -- --config group_imports=StdExternalCrate,imports_granularity=Module" +clippy-stacks = "clippy -p libstackerdb -p stacks-signer -p pox-locking -p clarity -p libsigner -p stacks-common --no-deps --tests --all-features -- -D warnings" # Uncomment to improve performance slightly, at the cost of portability # * Note that native binaries may not run on CPUs that are different from the build machine diff --git a/.github/workflows/clippy.yml b/.github/workflows/clippy.yml index 1ba4825527..e9fd90e9a2 100644 --- a/.github/workflows/clippy.yml +++ b/.github/workflows/clippy.yml @@ -20,21 +20,8 @@ jobs: name: Clippy Check runs-on: ubuntu-latest steps: - - name: Checkout the latest code - id: git_checkout - uses: actions/checkout@v3 - - name: Define Rust Toolchain - id: define_rust_toolchain - run: echo "RUST_TOOLCHAIN=$(cat ./rust-toolchain)" >> $GITHUB_ENV - - name: Setup Rust Toolchain - id: setup_rust_toolchain - uses: actions-rust-lang/setup-rust-toolchain@v1 - with: - toolchain: ${{ env.RUST_TOOLCHAIN }} - components: clippy - name: Clippy id: clippy uses: actions-rs/clippy-check@v1 with: - token: ${{ secrets.GITHUB_TOKEN }} - args: -p libstackerdb -p stacks-signer -p pox-locking -p clarity -p libsigner -p stacks-common --no-deps --tests --all-features -- -D warnings \ No newline at end of file + alias: "clippy-stacks" \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b8c63abc2c..c919de1a95 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -81,7 +81,7 @@ fix: incorporate unlocks in mempool admitter, #3623 ### Recommended githooks -It is helpful to set up the pre-commit git hook set up, so that Rust formatting issues are caught before +It is helpful to set up the pre-commit git hook set up, so that Rust formatting issues and clippy warnings are caught before you push your code. Follow these instruction to set it up: 1. Rename `.git/hooks/pre-commit.sample` to `.git/hooks/pre-commit` @@ -89,10 +89,16 @@ you push your code. Follow these instruction to set it up: ```sh #!/bin/sh +# Format staged Rust files git diff --name-only --staged | grep '\.rs$' | xargs -P 8 -I {} rustfmt {} --edition 2021 --check --config group_imports=StdExternalCrate,imports_granularity=Module || ( echo 'rustfmt failed: run "cargo fmt-stacks"'; exit 1 ) +# Run cargo clippy-stacks and fail the commit if there are any warnings +if ! cargo clippy-stacks; then + echo 'cargo clippy-stacks failed: fix the warnings and try again.'; + exit 1 +fi ``` 3. Make it executable by running `chmod +x .git/hooks/pre-commit` @@ -387,6 +393,18 @@ You can automatically reformat your commit via: cargo fmt-stacks ``` +## Clippy Warnings + +PRs will be checked against `clippy` and will _fail_ if any clippy warnings are generated. +Unfortunately, not all existing clippy warnings have been addressed throughout stacks-core, so arguments must be passed via the command line. +Therefore, we handle `clippy` configurations using a Cargo alias: `cargo clippy-stacks` + +You can check what warnings need to be addressed locally via: + +```bash +cargo clippy-stacks +``` + ## Comments Comments are very important for the readability and correctness of the codebase. The purpose of comments is: From 0c1059c86e10cb34466515768a77f9f37b312d9e Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Wed, 22 Jan 2025 12:49:42 -0800 Subject: [PATCH 10/17] Do not suggest adding clippy to git hooks Signed-off-by: Jacinta Ferrant --- CONTRIBUTING.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c919de1a95..7c79fc286c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -81,7 +81,7 @@ fix: incorporate unlocks in mempool admitter, #3623 ### Recommended githooks -It is helpful to set up the pre-commit git hook set up, so that Rust formatting issues and clippy warnings are caught before +It is helpful to set up the pre-commit git hook set up, so that Rust formatting issues are caught before you push your code. Follow these instruction to set it up: 1. Rename `.git/hooks/pre-commit.sample` to `.git/hooks/pre-commit` @@ -89,16 +89,10 @@ you push your code. Follow these instruction to set it up: ```sh #!/bin/sh -# Format staged Rust files git diff --name-only --staged | grep '\.rs$' | xargs -P 8 -I {} rustfmt {} --edition 2021 --check --config group_imports=StdExternalCrate,imports_granularity=Module || ( echo 'rustfmt failed: run "cargo fmt-stacks"'; exit 1 ) -# Run cargo clippy-stacks and fail the commit if there are any warnings -if ! cargo clippy-stacks; then - echo 'cargo clippy-stacks failed: fix the warnings and try again.'; - exit 1 -fi ``` 3. Make it executable by running `chmod +x .git/hooks/pre-commit` From 94164e916ac6fb5f5d306d8028e8653e10374a92 Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Wed, 22 Jan 2025 13:23:26 -0800 Subject: [PATCH 11/17] Run clippy without clippy check Signed-off-by: Jacinta Ferrant --- .github/workflows/clippy.yml | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clippy.yml b/.github/workflows/clippy.yml index e9fd90e9a2..2279d42c88 100644 --- a/.github/workflows/clippy.yml +++ b/.github/workflows/clippy.yml @@ -20,8 +20,18 @@ jobs: name: Clippy Check runs-on: ubuntu-latest steps: + - name: Checkout the latest code + id: git_checkout + uses: actions/checkout@v3 + - name: Define Rust Toolchain + id: define_rust_toolchain + run: echo "RUST_TOOLCHAIN=$(cat ./rust-toolchain)" >> $GITHUB_ENV + - name: Setup Rust Toolchain + id: setup_rust_toolchain + uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + components: clippy - name: Clippy id: clippy - uses: actions-rs/clippy-check@v1 - with: - alias: "clippy-stacks" \ No newline at end of file + run: cargo clippy-stacks \ No newline at end of file From 589bee10e42042652042827dae25332b53d2567e Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Wed, 22 Jan 2025 13:26:44 -0800 Subject: [PATCH 12/17] Fix existing clippy warnings Signed-off-by: Jacinta Ferrant --- clarity/src/vm/ast/parser/v2/mod.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/clarity/src/vm/ast/parser/v2/mod.rs b/clarity/src/vm/ast/parser/v2/mod.rs index 4c46e76a4d..c8a7252498 100644 --- a/clarity/src/vm/ast/parser/v2/mod.rs +++ b/clarity/src/vm/ast/parser/v2/mod.rs @@ -1124,9 +1124,7 @@ pub fn parse_collect_diagnostics( mod tests { use super::*; use crate::vm::diagnostic::Level; - use crate::vm::types::{ - ASCIIData, CharType, PrincipalData, SequenceData, StandardPrincipalData, UTF8Data, - }; + use crate::vm::types::{ASCIIData, CharType, PrincipalData, SequenceData}; #[test] fn test_parse_int() { From b691268b2c64d6b1a2d2b25a30b58e3302e28269 Mon Sep 17 00:00:00 2001 From: Brice Dobry Date: Thu, 23 Jan 2025 10:21:32 -0500 Subject: [PATCH 13/17] chore: don't log the contract source on deploy error Logging the contract source is excessive. It can be retrieved if it is needed for debugging. --- stackslib/src/chainstate/stacks/db/transactions.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/stackslib/src/chainstate/stacks/db/transactions.rs b/stackslib/src/chainstate/stacks/db/transactions.rs index 88bbf73dfe..f004d909e0 100644 --- a/stackslib/src/chainstate/stacks/db/transactions.rs +++ b/stackslib/src/chainstate/stacks/db/transactions.rs @@ -1300,7 +1300,6 @@ impl StacksChainState { info!("Smart-contract processed with {}", err_type; "txid" => %tx.txid(), "contract" => %contract_id, - "code" => %contract_code_str, "error" => ?error); // When top-level code in a contract publish causes a runtime error, // the transaction is accepted, but the contract is not created. @@ -1345,7 +1344,6 @@ impl StacksChainState { info!("Smart-contract encountered an analysis error at runtime"; "txid" => %tx.txid(), "contract" => %contract_id, - "code" => %contract_code_str, "error" => %check_error); let receipt = @@ -1361,7 +1359,6 @@ impl StacksChainState { warn!("Unexpected analysis error invalidating transaction: if included, this will invalidate a block"; "txid" => %tx.txid(), "contract" => %contract_id, - "code" => %contract_code_str, "error" => %check_error); return Err(Error::ClarityError(clarity_error::Interpreter( InterpreterError::Unchecked(check_error), @@ -1372,7 +1369,6 @@ impl StacksChainState { error!("Unexpected error invalidating transaction: if included, this will invalidate a block"; "txid" => %tx.txid(), "contract_name" => %contract_id, - "code" => %contract_code_str, "error" => ?e); return Err(Error::ClarityError(e)); } From 9978402a120f1c9b3da830e0552b0b9c54e6adf4 Mon Sep 17 00:00:00 2001 From: Jeff Bencin Date: Thu, 23 Jan 2025 11:08:50 -0500 Subject: [PATCH 14/17] chore: Additional simplifications to `Vec` construction in clarity_cli.rs --- stackslib/src/clarity_cli.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/stackslib/src/clarity_cli.rs b/stackslib/src/clarity_cli.rs index 58b2e7895f..cc0ad11273 100644 --- a/stackslib/src/clarity_cli.rs +++ b/stackslib/src/clarity_cli.rs @@ -1002,7 +1002,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().cloned().collect(); + let mut argv = args.to_vec(); let mainnet = if let Ok(Some(_)) = consume_arg(&mut argv, &["--testnet"], false) { false @@ -1127,7 +1127,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option = args.into_iter().cloned().collect(); + let mut argv = args.to_vec(); let contract_id = if let Ok(optarg) = consume_arg(&mut argv, &["--contract_id"], true) { optarg .map(|optarg_str| { @@ -1253,7 +1253,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().cloned().collect(); + let mut argv = args.to_vec(); let mainnet = if let Ok(Some(_)) = consume_arg(&mut argv, &["--testnet"], false) { false } else { @@ -1281,15 +1281,15 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option ").unwrap_or_else(|e| { - panic!("Failed to write stdout prompt string:\n{}", e); + panic!("Failed to write stdout prompt string:\n{e}"); }); stdout.flush().unwrap_or_else(|e| { - panic!("Failed to flush stdout prompt string:\n{}", e); + panic!("Failed to flush stdout prompt string:\n{e}"); }); match io::stdin().read_line(&mut buffer) { Ok(_) => buffer, Err(error) => { - eprintln!("Error reading from stdin:\n{}", error); + eprintln!("Error reading from stdin:\n{error}"); panic_test!(); } } @@ -1385,7 +1385,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().cloned().collect(); + let mut argv = args.to_vec(); let costs = if let Ok(Some(_)) = consume_arg(&mut argv, &["--costs"], false) { true @@ -1448,7 +1448,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().cloned().collect(); + let mut argv = args.to_vec(); let costs = if let Ok(Some(_)) = consume_arg(&mut argv, &["--costs"], false) { true @@ -1530,7 +1530,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().cloned().collect(); + let mut argv = args.to_vec(); let costs = if let Ok(Some(_)) = consume_arg(&mut argv, &["--costs"], false) { true @@ -1612,7 +1612,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().cloned().collect(); + let mut argv = args.to_vec(); let coverage_folder = if let Ok(covarg) = consume_arg(&mut argv, &["--c"], true) { covarg } else { @@ -1767,7 +1767,7 @@ pub fn invoke_command(invoked_by: &str, args: &[String]) -> (i32, Option { - let mut argv: Vec = args.into_iter().cloned().collect(); + let mut argv = args.to_vec(); let coverage_folder = if let Ok(covarg) = consume_arg(&mut argv, &["--c"], true) { covarg } else { From 47a0d911ccfea964b5b7407ee95cafde56ba42d2 Mon Sep 17 00:00:00 2001 From: Jude Nelson Date: Thu, 23 Jan 2025 12:57:56 -0500 Subject: [PATCH 15/17] chore: refactor StacksAddress and PrincipalData to make them easier to use --- .github/workflows/bitcoin-tests.yml | 1 + clarity/src/libclarity.rs | 3 +- clarity/src/vm/contexts.rs | 14 +- clarity/src/vm/functions/conversions.rs | 4 + clarity/src/vm/functions/crypto.rs | 7 +- clarity/src/vm/functions/principals.rs | 19 +- clarity/src/vm/test_util/mod.rs | 2 +- clarity/src/vm/tests/principals.rs | 25 +- clarity/src/vm/tests/simple_apply_eval.rs | 12 +- clarity/src/vm/types/mod.rs | 134 ++-- clarity/src/vm/types/serialization.rs | 17 +- clarity/src/vm/types/signatures.rs | 4 +- libstackerdb/src/libstackerdb.rs | 2 +- libstackerdb/src/tests/mod.rs | 5 +- stacks-common/src/types/chainstate.rs | 66 +- stacks-common/src/types/mod.rs | 45 +- stacks-signer/src/cli.rs | 10 +- stacks-signer/src/v0/signer.rs | 4 +- stackslib/src/blockstack_cli.rs | 2 +- stackslib/src/burnchains/tests/db.rs | 5 +- stackslib/src/chainstate/burn/db/sortdb.rs | 38 +- .../burn/operations/delegate_stx.rs | 50 +- .../burn/operations/leader_block_commit.rs | 12 +- .../src/chainstate/burn/operations/mod.rs | 4 +- .../chainstate/burn/operations/stack_stx.rs | 30 +- .../burn/operations/test/serialization.rs | 15 +- .../burn/operations/transfer_stx.rs | 5 +- .../burn/operations/vote_for_aggregate_key.rs | 15 +- .../chainstate/nakamoto/coordinator/tests.rs | 14 +- stackslib/src/chainstate/nakamoto/mod.rs | 8 +- .../src/chainstate/nakamoto/test_signers.rs | 9 +- .../src/chainstate/nakamoto/tests/mod.rs | 9 +- .../src/chainstate/nakamoto/tests/node.rs | 2 +- stackslib/src/chainstate/stacks/address.rs | 274 +++----- stackslib/src/chainstate/stacks/auth.rs | 106 ++- stackslib/src/chainstate/stacks/block.rs | 20 +- .../chainstate/stacks/boot/contract_tests.rs | 6 +- stackslib/src/chainstate/stacks/boot/mod.rs | 76 +- .../src/chainstate/stacks/boot/pox_2_tests.rs | 147 ++-- .../src/chainstate/stacks/boot/pox_3_tests.rs | 137 ++-- .../src/chainstate/stacks/boot/pox_4_tests.rs | 493 +++++++++++-- .../src/chainstate/stacks/db/accounts.rs | 15 +- stackslib/src/chainstate/stacks/db/blocks.rs | 2 +- stackslib/src/chainstate/stacks/db/mod.rs | 19 +- .../src/chainstate/stacks/db/transactions.rs | 507 ++++++++++++-- stackslib/src/chainstate/stacks/mod.rs | 45 +- .../stacks/tests/chain_histories.rs | 3 +- .../src/chainstate/stacks/transaction.rs | 648 +++++++++--------- stackslib/src/config/chain_data.rs | 9 +- stackslib/src/core/tests/mod.rs | 103 +-- .../cost_estimates/tests/cost_estimators.rs | 10 +- .../src/cost_estimates/tests/fee_medians.rs | 2 +- .../src/cost_estimates/tests/fee_scalar.rs | 4 +- .../src/net/api/tests/postblock_proposal.rs | 5 +- .../src/net/api/tests/postmempoolquery.rs | 10 +- stackslib/src/net/codec.rs | 14 +- stackslib/src/net/db.rs | 40 +- stackslib/src/net/stackerdb/tests/config.rs | 39 +- stackslib/src/net/stackerdb/tests/db.rs | 223 ++---- stackslib/src/net/stackerdb/tests/sync.rs | 18 +- stackslib/src/net/tests/convergence.rs | 2 +- stackslib/src/net/tests/httpcore.rs | 5 +- stackslib/src/net/tests/mempool/mod.rs | 30 +- stackslib/src/net/tests/mod.rs | 2 +- stackslib/src/util_lib/boot.rs | 2 +- .../src/util_lib/signed_structured_data.rs | 4 +- testnet/stacks-node/src/tests/epoch_21.rs | 2 +- testnet/stacks-node/src/tests/epoch_22.rs | 18 +- testnet/stacks-node/src/tests/epoch_24.rs | 24 +- testnet/stacks-node/src/tests/mempool.rs | 10 +- .../src/tests/nakamoto_integrations.rs | 129 +++- .../src/tests/neon_integrations.rs | 2 +- testnet/stacks-node/src/tests/signer/v0.rs | 6 +- 73 files changed, 2274 insertions(+), 1529 deletions(-) diff --git a/.github/workflows/bitcoin-tests.yml b/.github/workflows/bitcoin-tests.yml index bb64a1a8b7..363e02044f 100644 --- a/.github/workflows/bitcoin-tests.yml +++ b/.github/workflows/bitcoin-tests.yml @@ -167,6 +167,7 @@ jobs: - tests::nakamoto_integrations::sip029_coinbase_change - tests::nakamoto_integrations::clarity_cost_spend_down - tests::nakamoto_integrations::v3_blockbyheight_api_endpoint + - tests::nakamoto_integrations::mine_invalid_principal_from_consensus_buff - tests::nakamoto_integrations::test_tenure_extend_from_flashblocks # TODO: enable these once v1 signer is supported by a new nakamoto epoch # - tests::signer::v1::dkg diff --git a/clarity/src/libclarity.rs b/clarity/src/libclarity.rs index 7ce2a4f903..9f1a0a06ba 100644 --- a/clarity/src/libclarity.rs +++ b/clarity/src/libclarity.rs @@ -60,7 +60,8 @@ pub mod boot_util { pub fn boot_code_id(name: &str, mainnet: bool) -> QualifiedContractIdentifier { let addr = boot_code_addr(mainnet); QualifiedContractIdentifier::new( - addr.into(), + addr.try_into() + .expect("FATAL: boot contract addr is not a legal principal"), ContractName::try_from(name.to_string()) .expect("FATAL: boot contract name is not a legal ContractName"), ) diff --git a/clarity/src/vm/contexts.rs b/clarity/src/vm/contexts.rs index c8050f6803..c716538f6d 100644 --- a/clarity/src/vm/contexts.rs +++ b/clarity/src/vm/contexts.rs @@ -2134,20 +2134,14 @@ mod test { mut tl_env_factory: TopLevelMemoryEnvironmentGenerator, ) { let mut env = tl_env_factory.get_env(epoch); - let u1 = StacksAddress { - version: 0, - bytes: Hash160([1; 20]), - }; - let u2 = StacksAddress { - version: 0, - bytes: Hash160([2; 20]), - }; + let u1 = StacksAddress::new(0, Hash160([1; 20])).unwrap(); + let u2 = StacksAddress::new(0, Hash160([2; 20])).unwrap(); // insufficient balance must be a non-includable transaction. it must error here, // not simply rollback the tx and squelch the error as includable. let e = env .stx_transfer( - &PrincipalData::from(u1), - &PrincipalData::from(u2), + &PrincipalData::try_from(u1).unwrap(), + &PrincipalData::try_from(u2).unwrap(), 1000, &BuffData::empty(), ) diff --git a/clarity/src/vm/functions/conversions.rs b/clarity/src/vm/functions/conversions.rs index 29fa7df651..db4c35fc71 100644 --- a/clarity/src/vm/functions/conversions.rs +++ b/clarity/src/vm/functions/conversions.rs @@ -20,6 +20,7 @@ use crate::vm::errors::{ check_argument_count, CheckErrors, InterpreterError, InterpreterResult as Result, }; use crate::vm::representations::SymbolicExpression; +use crate::vm::types::serialization::SerializationError; use crate::vm::types::SequenceSubtype::BufferType; use crate::vm::types::TypeSignature::SequenceType; use crate::vm::types::{ @@ -276,6 +277,9 @@ pub fn from_consensus_buff( env.epoch().value_sanitizing(), ) { Ok(value) => value, + Err(SerializationError::UnexpectedSerialization) => { + return Err(CheckErrors::Expects("UnexpectedSerialization".into()).into()) + } Err(_) => return Ok(Value::none()), }; if !type_arg.admits(env.epoch(), &result)? { diff --git a/clarity/src/vm/functions/crypto.rs b/clarity/src/vm/functions/crypto.rs index 9cc5f5ae9b..1dd92a8f8f 100644 --- a/clarity/src/vm/functions/crypto.rs +++ b/clarity/src/vm/functions/crypto.rs @@ -27,10 +27,7 @@ use crate::vm::errors::{ check_argument_count, CheckErrors, InterpreterError, InterpreterResult as Result, }; use crate::vm::representations::SymbolicExpression; -use crate::vm::types::{ - BuffData, SequenceData, StacksAddressExtensions, TypeSignature, Value, BUFF_32, BUFF_33, - BUFF_65, -}; +use crate::vm::types::{BuffData, SequenceData, TypeSignature, Value, BUFF_32, BUFF_33, BUFF_65}; use crate::vm::{eval, ClarityVersion, Environment, LocalContext}; macro_rules! native_hash_func { @@ -120,7 +117,7 @@ pub fn special_principal_of( } else { pubkey_to_address_v1(pub_key)? }; - let principal = addr.to_account_principal(); + let principal = addr.into(); Ok(Value::okay(Value::Principal(principal)) .map_err(|_| InterpreterError::Expect("Failed to construct ok".into()))?) } else { diff --git a/clarity/src/vm/functions/principals.rs b/clarity/src/vm/functions/principals.rs index e34e50148e..c3600e6654 100644 --- a/clarity/src/vm/functions/principals.rs +++ b/clarity/src/vm/functions/principals.rs @@ -58,15 +58,10 @@ pub fn special_is_standard( runtime_cost(ClarityCostFunction::IsStandard, env, 0)?; let owner = eval(&args[0], env, context)?; - let version = match owner { - Value::Principal(PrincipalData::Standard(StandardPrincipalData(version, _bytes))) => { - version - } - Value::Principal(PrincipalData::Contract(QualifiedContractIdentifier { - issuer, - name: _, - })) => issuer.0, - _ => return Err(CheckErrors::TypeValueError(TypeSignature::PrincipalType, owner).into()), + let version = if let Value::Principal(ref p) = owner { + p.version() + } else { + return Err(CheckErrors::TypeValueError(TypeSignature::PrincipalType, owner).into()); }; Ok(Value::Bool(version_matches_current_network( @@ -161,10 +156,12 @@ pub fn special_principal_destruct( let principal = eval(&args[0], env, context)?; let (version_byte, hash_bytes, name_opt) = match principal { - Value::Principal(PrincipalData::Standard(StandardPrincipalData(version, bytes))) => { + Value::Principal(PrincipalData::Standard(p)) => { + let (version, bytes) = p.destruct(); (version, bytes, None) } Value::Principal(PrincipalData::Contract(QualifiedContractIdentifier { issuer, name })) => { + let issuer = issuer.destruct(); (issuer.0, issuer.1, Some(name)) } _ => { @@ -254,7 +251,7 @@ pub fn special_principal_construct( // Construct the principal. let mut transfer_buffer = [0u8; 20]; transfer_buffer.copy_from_slice(verified_hash_bytes); - let principal_data = StandardPrincipalData(version_byte, transfer_buffer); + let principal_data = StandardPrincipalData::new(version_byte, transfer_buffer)?; let principal = if let Some(name) = name_opt { // requested a contract principal. Verify that the `name` is a valid ContractName. diff --git a/clarity/src/vm/test_util/mod.rs b/clarity/src/vm/test_util/mod.rs index 37a40182eb..07e557119c 100644 --- a/clarity/src/vm/test_util/mod.rs +++ b/clarity/src/vm/test_util/mod.rs @@ -108,7 +108,7 @@ impl From<&StacksPrivateKey> for StandardPrincipalData { &vec![StacksPublicKey::from_private(o)], ) .unwrap(); - StandardPrincipalData::from(stacks_addr) + StandardPrincipalData::try_from(stacks_addr).unwrap() } } diff --git a/clarity/src/vm/tests/principals.rs b/clarity/src/vm/tests/principals.rs index 98db149273..06fd3e546f 100644 --- a/clarity/src/vm/tests/principals.rs +++ b/clarity/src/vm/tests/principals.rs @@ -668,7 +668,7 @@ fn test_principal_construct_good() { Value::Response(ResponseData { committed: true, data: Box::new(Value::Principal(PrincipalData::Standard( - StandardPrincipalData(22, transfer_buffer) + StandardPrincipalData::new(22, transfer_buffer).unwrap() ))) }), execute_with_parameters( @@ -688,7 +688,7 @@ fn test_principal_construct_good() { Value::Response(ResponseData { committed: true, data: Box::new(Value::Principal(PrincipalData::Standard( - StandardPrincipalData(20, transfer_buffer) + StandardPrincipalData::new(20, transfer_buffer).unwrap() ))) }), execute_with_parameters( @@ -710,7 +710,7 @@ fn test_principal_construct_good() { committed: true, data: Box::new(Value::Principal(PrincipalData::Contract( QualifiedContractIdentifier::new( - StandardPrincipalData(22, transfer_buffer), + StandardPrincipalData::new(22, transfer_buffer).unwrap(), "hello-world".into() ) ))) @@ -734,7 +734,7 @@ fn test_principal_construct_good() { committed: true, data: Box::new(Value::Principal(PrincipalData::Contract( QualifiedContractIdentifier::new( - StandardPrincipalData(20, transfer_buffer), + StandardPrincipalData::new(20, transfer_buffer).unwrap(), "hello-world".into() ) ))) @@ -756,7 +756,7 @@ fn test_principal_construct_good() { Value::Response(ResponseData { committed: true, data: Box::new(Value::Principal(PrincipalData::Standard( - StandardPrincipalData(26, transfer_buffer) + StandardPrincipalData::new(26, transfer_buffer).unwrap() ))) }), execute_with_parameters( @@ -776,7 +776,7 @@ fn test_principal_construct_good() { Value::Response(ResponseData { committed: true, data: Box::new(Value::Principal(PrincipalData::Standard( - StandardPrincipalData(21, transfer_buffer) + StandardPrincipalData::new(21, transfer_buffer).unwrap() ))) }), execute_with_parameters( @@ -798,7 +798,7 @@ fn test_principal_construct_good() { committed: true, data: Box::new(Value::Principal(PrincipalData::Contract( QualifiedContractIdentifier::new( - StandardPrincipalData(26, transfer_buffer), + StandardPrincipalData::new(26, transfer_buffer).unwrap(), "hello-world".into() ) ))) @@ -822,7 +822,7 @@ fn test_principal_construct_good() { committed: true, data: Box::new(Value::Principal(PrincipalData::Contract( QualifiedContractIdentifier::new( - StandardPrincipalData(21, transfer_buffer), + StandardPrincipalData::new(21, transfer_buffer).unwrap(), "hello-world".into() ) ))) @@ -853,15 +853,14 @@ fn create_principal_from_strings( if let Some(name) = name { // contract principal requested Value::Principal(PrincipalData::Contract(QualifiedContractIdentifier::new( - StandardPrincipalData(version_array[0], principal_array), + StandardPrincipalData::new(version_array[0], principal_array).unwrap(), name.into(), ))) } else { // standard principal requested - Value::Principal(PrincipalData::Standard(StandardPrincipalData( - version_array[0], - principal_array, - ))) + Value::Principal(PrincipalData::Standard( + StandardPrincipalData::new(version_array[0], principal_array).unwrap(), + )) } } diff --git a/clarity/src/vm/tests/simple_apply_eval.rs b/clarity/src/vm/tests/simple_apply_eval.rs index f6dbd87090..861cf60224 100644 --- a/clarity/src/vm/tests/simple_apply_eval.rs +++ b/clarity/src/vm/tests/simple_apply_eval.rs @@ -430,7 +430,7 @@ fn test_secp256k1() { ) .unwrap(); eprintln!("addr from privk {:?}", &addr); - let principal = addr.to_account_principal(); + let principal = addr.try_into().unwrap(); if let PrincipalData::Standard(data) = principal { eprintln!("test_secp256k1 principal {:?}", data.to_address()); } @@ -446,7 +446,7 @@ fn test_secp256k1() { ) .unwrap(); eprintln!("addr from hex {:?}", addr); - let principal = addr.to_account_principal(); + let principal: PrincipalData = addr.try_into().unwrap(); if let PrincipalData::Standard(data) = principal.clone() { eprintln!("test_secp256k1 principal {:?}", data.to_address()); } @@ -491,8 +491,9 @@ fn test_principal_of_fix() { .unwrap()], ) .unwrap() - .to_account_principal(); - let testnet_principal = StacksAddress::from_public_keys( + .try_into() + .unwrap(); + let testnet_principal: PrincipalData = StacksAddress::from_public_keys( C32_ADDRESS_VERSION_TESTNET_SINGLESIG, &AddressHashMode::SerializeP2PKH, 1, @@ -502,7 +503,8 @@ fn test_principal_of_fix() { .unwrap()], ) .unwrap() - .to_account_principal(); + .try_into() + .unwrap(); // Clarity2, mainnet, should have a mainnet principal. assert_eq!( diff --git a/clarity/src/vm/types/mod.rs b/clarity/src/vm/types/mod.rs index e789676f5c..804d5f2eb1 100644 --- a/clarity/src/vm/types/mod.rs +++ b/clarity/src/vm/types/mod.rs @@ -66,15 +66,72 @@ pub struct ListData { pub type_signature: ListTypeData, } -#[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)] -pub struct StandardPrincipalData(pub u8, pub [u8; 20]); - -impl StandardPrincipalData { - pub fn transient() -> StandardPrincipalData { - Self( - 1, - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], - ) +pub use self::std_principals::StandardPrincipalData; + +mod std_principals { + use std::fmt; + + use stacks_common::address::c32; + + use crate::vm::errors::InterpreterError; + + #[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)] + pub struct StandardPrincipalData(u8, pub [u8; 20]); + + impl StandardPrincipalData { + pub fn transient() -> StandardPrincipalData { + Self( + 1, + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + ) + } + } + + impl StandardPrincipalData { + pub fn new(version: u8, bytes: [u8; 20]) -> Result { + if version >= 32 { + return Err(InterpreterError::Expect("Unexpected principal data".into())); + } + Ok(Self(version, bytes)) + } + + /// NEVER, EVER use this in ANY production code. + /// `version` must NEVER be greater than 31. + #[cfg(any(test, feature = "testing"))] + pub fn new_unsafe(version: u8, bytes: [u8; 20]) -> Self { + Self(version, bytes) + } + + pub fn null_principal() -> Self { + Self::new(0, [0; 20]).unwrap() + } + + pub fn version(&self) -> u8 { + self.0 + } + + pub fn to_address(&self) -> String { + c32::c32_address(self.0, &self.1[..]).unwrap_or_else(|_| "INVALID_C32_ADD".to_string()) + } + + pub fn destruct(self) -> (u8, [u8; 20]) { + let Self(version, bytes) = self; + (version, bytes) + } + } + + impl fmt::Display for StandardPrincipalData { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let c32_str = self.to_address(); + write!(f, "{}", c32_str) + } + } + + impl fmt::Debug for StandardPrincipalData { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let c32_str = self.to_address(); + write!(f, "StandardPrincipalData({})", c32_str) + } } } @@ -169,7 +226,9 @@ pub trait StacksAddressExtensions { impl StacksAddressExtensions for StacksAddress { fn to_account_principal(&self) -> PrincipalData { - PrincipalData::Standard(StandardPrincipalData(self.version, *self.bytes.as_bytes())) + PrincipalData::Standard( + StandardPrincipalData::new(self.version(), *self.bytes().as_bytes()).unwrap(), + ) } } @@ -1372,11 +1431,20 @@ impl fmt::Display for Value { impl PrincipalData { pub fn version(&self) -> u8 { match self { - PrincipalData::Standard(StandardPrincipalData(version, _)) => *version, - PrincipalData::Contract(QualifiedContractIdentifier { issuer, name: _ }) => issuer.0, + PrincipalData::Standard(ref p) => p.version(), + PrincipalData::Contract(QualifiedContractIdentifier { issuer, name: _ }) => { + issuer.version() + } } } + /// A version is only valid if it fits into 5 bits. + /// This is enforced by the constructor, but it was historically possible to assemble invalid + /// addresses. This function is used to validate historic addresses. + pub fn has_valid_version(&self) -> bool { + self.version() < 32 + } + pub fn parse(literal: &str) -> Result { // be permissive about leading single-quote let literal = literal.strip_prefix('\'').unwrap_or(literal); @@ -1405,27 +1473,7 @@ impl PrincipalData { } let mut fixed_data = [0; 20]; fixed_data.copy_from_slice(&data[..20]); - Ok(StandardPrincipalData(version, fixed_data)) - } -} - -impl StandardPrincipalData { - pub fn to_address(&self) -> String { - c32::c32_address(self.0, &self.1[..]).unwrap_or_else(|_| "INVALID_C32_ADD".to_string()) - } -} - -impl fmt::Display for StandardPrincipalData { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let c32_str = self.to_address(); - write!(f, "{}", c32_str) - } -} - -impl fmt::Debug for StandardPrincipalData { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let c32_str = self.to_address(); - write!(f, "StandardPrincipalData({})", c32_str) + Ok(StandardPrincipalData::new(version, fixed_data)?) } } @@ -1463,23 +1511,29 @@ impl fmt::Display for TraitIdentifier { } impl From for StandardPrincipalData { - fn from(addr: StacksAddress) -> StandardPrincipalData { - StandardPrincipalData(addr.version, addr.bytes.0) + fn from(addr: StacksAddress) -> Self { + let (version, bytes) = addr.destruct(); + + // should be infallible because it's impossible to construct a StacksAddress with an + // unsupported version byte + Self::new(version, bytes.0) + .expect("FATAL: could not convert StacksAddress to StandardPrincipalData") } } impl From for PrincipalData { - fn from(addr: StacksAddress) -> PrincipalData { + fn from(addr: StacksAddress) -> Self { PrincipalData::from(StandardPrincipalData::from(addr)) } } impl From for StacksAddress { fn from(o: StandardPrincipalData) -> StacksAddress { - StacksAddress { - version: o.0, - bytes: hash::Hash160(o.1), - } + // should be infallible because it's impossible to construct a StandardPrincipalData with + // an unsupported version byte + StacksAddress::new(o.version(), hash::Hash160(o.1)).unwrap_or_else(|_| { + panic!("FATAL: could not convert a StandardPrincipalData to StacksAddress") + }) } } diff --git a/clarity/src/vm/types/serialization.rs b/clarity/src/vm/types/serialization.rs index 57bce8bb6c..52ec60af2f 100644 --- a/clarity/src/vm/types/serialization.rs +++ b/clarity/src/vm/types/serialization.rs @@ -47,6 +47,7 @@ pub enum SerializationError { DeserializeExpected(TypeSignature), LeftoverBytesInDeserialization, SerializationError(String), + UnexpectedSerialization, } lazy_static! { @@ -90,6 +91,9 @@ impl std::fmt::Display for SerializationError { "Deserialization expected the type of the input to be: {}", e ), + SerializationError::UnexpectedSerialization => { + write!(f, "The serializer handled an input in an unexpected way") + } SerializationError::LeftoverBytesInDeserialization => { write!(f, "Deserialization error: bytes left over in buffer") } @@ -201,7 +205,7 @@ trait ClarityValueSerializable { impl ClarityValueSerializable for StandardPrincipalData { fn serialize_write(&self, w: &mut W) -> std::io::Result<()> { - w.write_all(&[self.0])?; + w.write_all(&[self.version()])?; w.write_all(&self.1) } @@ -210,7 +214,8 @@ impl ClarityValueSerializable for StandardPrincipalData { let mut data = [0; 20]; r.read_exact(&mut version)?; r.read_exact(&mut data)?; - Ok(StandardPrincipalData(version[0], data)) + StandardPrincipalData::new(version[0], data) + .map_err(|_| SerializationError::UnexpectedSerialization) } } @@ -2110,16 +2115,16 @@ pub mod tests { ("03", Ok(Value::Bool(true))), ("04", Ok(Value::Bool(false))), ("050011deadbeef11ababffff11deadbeef11ababffff", Ok( - StandardPrincipalData( + StandardPrincipalData::new( 0x00, [0x11, 0xde, 0xad, 0xbe, 0xef, 0x11, 0xab, 0xab, 0xff, 0xff, - 0x11, 0xde, 0xad, 0xbe, 0xef, 0x11, 0xab, 0xab, 0xff, 0xff]).into())), + 0x11, 0xde, 0xad, 0xbe, 0xef, 0x11, 0xab, 0xab, 0xff, 0xff]).unwrap().into())), ("060011deadbeef11ababffff11deadbeef11ababffff0461626364", Ok( QualifiedContractIdentifier::new( - StandardPrincipalData( + StandardPrincipalData::new( 0x00, [0x11, 0xde, 0xad, 0xbe, 0xef, 0x11, 0xab, 0xab, 0xff, 0xff, - 0x11, 0xde, 0xad, 0xbe, 0xef, 0x11, 0xab, 0xab, 0xff, 0xff]), + 0x11, 0xde, 0xad, 0xbe, 0xef, 0x11, 0xab, 0xab, 0xff, 0xff]).unwrap(), "abcd".into()).into())), ("0700ffffffffffffffffffffffffffffffff", Ok(Value::okay(Value::Int(-1)).unwrap())), ("0800ffffffffffffffffffffffffffffffff", Ok(Value::error(Value::Int(-1)).unwrap())), diff --git a/clarity/src/vm/types/signatures.rs b/clarity/src/vm/types/signatures.rs index e76c7e034d..f41b8ed1a3 100644 --- a/clarity/src/vm/types/signatures.rs +++ b/clarity/src/vm/types/signatures.rs @@ -50,7 +50,7 @@ impl AssetIdentifier { pub fn STX() -> AssetIdentifier { AssetIdentifier { contract_identifier: QualifiedContractIdentifier::new( - StandardPrincipalData(0, [0u8; 20]), + StandardPrincipalData::null_principal(), ContractName::try_from("STX".to_string()).unwrap(), ), asset_name: ClarityName::try_from("STX".to_string()).unwrap(), @@ -61,7 +61,7 @@ impl AssetIdentifier { pub fn STX_burned() -> AssetIdentifier { AssetIdentifier { contract_identifier: QualifiedContractIdentifier::new( - StandardPrincipalData(0, [0u8; 20]), + StandardPrincipalData::null_principal(), ContractName::try_from("BURNED".to_string()).unwrap(), ), asset_name: ClarityName::try_from("BURNED".to_string()).unwrap(), diff --git a/libstackerdb/src/libstackerdb.rs b/libstackerdb/src/libstackerdb.rs index 36d7dd3643..539025d197 100644 --- a/libstackerdb/src/libstackerdb.rs +++ b/libstackerdb/src/libstackerdb.rs @@ -186,7 +186,7 @@ impl SlotMetadata { .map_err(|ve| Error::VerifyingError(ve.to_string()))?; let pubkh = Hash160::from_node_public_key(&pubk); - Ok(pubkh == principal.bytes) + Ok(pubkh == *principal.bytes()) } } diff --git a/libstackerdb/src/tests/mod.rs b/libstackerdb/src/tests/mod.rs index b0135eb72d..f0e166a67b 100644 --- a/libstackerdb/src/tests/mod.rs +++ b/libstackerdb/src/tests/mod.rs @@ -32,10 +32,7 @@ fn test_stackerdb_slot_metadata_sign_verify() { &vec![StacksPublicKey::from_private(&pk)], ) .unwrap(); - let bad_addr = StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]), - }; + let bad_addr = StacksAddress::new(0x01, Hash160([0x01; 20])).unwrap(); let chunk_data = StackerDBChunkData { slot_id: 0, diff --git a/stacks-common/src/types/chainstate.rs b/stacks-common/src/types/chainstate.rs index 630ce70c9d..59052ff3a9 100644 --- a/stacks-common/src/types/chainstate.rs +++ b/stacks-common/src/types/chainstate.rs @@ -1,3 +1,19 @@ +// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation +// Copyright (C) 2020-2025 Stacks Open Internet Foundation +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + use std::fmt::{self, Display}; use std::io::{Read, Write}; use std::str::FromStr; @@ -9,6 +25,7 @@ use serde::ser::Error as ser_Error; use serde::Serialize; use sha2::{Digest as Sha2Digest, Sha256, Sha512_256}; +use crate::address::Error as AddressError; use crate::codec::{read_next, write_next, Error as CodecError, StacksMessageCodec}; use crate::consts::{FIRST_BURNCHAIN_CONSENSUS_HASH, FIRST_STACKS_BLOCK_HASH}; use crate::deps_common::bitcoin::util::hash::Sha256dHash; @@ -277,8 +294,48 @@ impl fmt::Display for PoxId { #[derive(Debug, Clone, PartialEq, Eq, Copy, Serialize, Deserialize, Hash)] pub struct StacksAddress { - pub version: u8, - pub bytes: Hash160, + version: u8, + bytes: Hash160, +} + +impl StacksAddress { + pub fn new(version: u8, hash: Hash160) -> Result { + if version >= 32 { + return Err(AddressError::InvalidVersion(version)); + } + + Ok(StacksAddress { + version, + bytes: hash, + }) + } + + // NEVER, EVER use this in ANY production code! + // It should never be possible to construct an address with a version greater than 31 + #[cfg(any(test, feature = "testing"))] + pub fn new_unsafe(version: u8, bytes: Hash160) -> Self { + Self { version, bytes } + } + + pub fn version(&self) -> u8 { + self.version + } + + pub fn bytes(&self) -> &Hash160 { + &self.bytes + } + + pub fn destruct(self) -> (u8, Hash160) { + (self.version, self.bytes) + } + + /// Because addresses are crockford-32 encoded, the version must be a 5-bit number. + /// Historically, it was possible to construct invalid addresses given that we use a u8 to + /// represent the version. This function is used to validate addresses before relying on their + /// version. + pub fn has_valid_version(&self) -> bool { + self.version < 32 + } } impl StacksMessageCodec for StacksAddress { @@ -290,6 +347,11 @@ impl StacksMessageCodec for StacksAddress { fn consensus_deserialize(fd: &mut R) -> Result { let version: u8 = read_next(fd)?; + if version >= 32 { + return Err(CodecError::DeserializeError( + "Address version byte must be in range 0 to 31".into(), + )); + } let hash160: Hash160 = read_next(fd)?; Ok(StacksAddress { version, diff --git a/stacks-common/src/types/mod.rs b/stacks-common/src/types/mod.rs index 07201b4888..de8db644fa 100644 --- a/stacks-common/src/types/mod.rs +++ b/stacks-common/src/types/mod.rs @@ -591,23 +591,16 @@ impl PartialOrd for StacksAddress { impl Ord for StacksAddress { fn cmp(&self, other: &StacksAddress) -> Ordering { - match self.version.cmp(&other.version) { - Ordering::Equal => self.bytes.cmp(&other.bytes), + match self.version().cmp(&other.version()) { + Ordering::Equal => self.bytes().cmp(&other.bytes()), inequality => inequality, } } } impl StacksAddress { - pub fn new(version: u8, hash: Hash160) -> StacksAddress { - StacksAddress { - version, - bytes: hash, - } - } - pub fn is_mainnet(&self) -> bool { - match self.version { + match self.version() { C32_ADDRESS_VERSION_MAINNET_MULTISIG | C32_ADDRESS_VERSION_MAINNET_SINGLESIG => true, C32_ADDRESS_VERSION_TESTNET_MULTISIG | C32_ADDRESS_VERSION_TESTNET_SINGLESIG => false, _ => false, @@ -615,14 +608,16 @@ impl StacksAddress { } pub fn burn_address(mainnet: bool) -> StacksAddress { - StacksAddress { - version: if mainnet { + Self::new( + if mainnet { C32_ADDRESS_VERSION_MAINNET_SINGLESIG } else { C32_ADDRESS_VERSION_TESTNET_SINGLESIG }, - bytes: Hash160([0u8; 20]), - } + Hash160([0u8; 20]), + ) + .unwrap_or_else(|_| panic!("FATAL: constant address versions are invalid")) + // infallible } /// Generate an address from a given address hash mode, signature threshold, and list of public @@ -663,7 +658,7 @@ impl StacksAddress { } let hash_bits = public_keys_to_address_hash(hash_mode, num_sigs, pubkeys); - Some(StacksAddress::new(version, hash_bits)) + StacksAddress::new(version, hash_bits).ok() } /// Make a P2PKH StacksAddress @@ -679,16 +674,17 @@ impl StacksAddress { } else { C32_ADDRESS_VERSION_TESTNET_SINGLESIG }; - Self { - version, - bytes: hash, - } + Self::new(version, hash) + .unwrap_or_else(|_| panic!("FATAL: constant address versions are invalid")) + // infallible } } impl std::fmt::Display for StacksAddress { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - c32_address(self.version, self.bytes.as_bytes()) + // the .unwrap_or_else() should be unreachable since StacksAddress is constructed to only + // accept a 5-bit value for its version + c32_address(self.version(), self.bytes().as_bytes()) .expect("Stacks version is not C32-encodable") .fmt(f) } @@ -696,7 +692,7 @@ impl std::fmt::Display for StacksAddress { impl Address for StacksAddress { fn to_bytes(&self) -> Vec { - self.bytes.as_bytes().to_vec() + self.bytes().as_bytes().to_vec() } fn from_string(s: &str) -> Option { @@ -708,14 +704,11 @@ impl Address for StacksAddress { let mut hash_bytes = [0u8; 20]; hash_bytes.copy_from_slice(&bytes[..]); - Some(StacksAddress { - version, - bytes: Hash160(hash_bytes), - }) + StacksAddress::new(version, Hash160(hash_bytes)).ok() } fn is_burn(&self) -> bool { - self.bytes == Hash160([0u8; 20]) + self.bytes() == &Hash160([0u8; 20]) } } diff --git a/stacks-signer/src/cli.rs b/stacks-signer/src/cli.rs index 7b666d3762..5d5b8806e7 100644 --- a/stacks-signer/src/cli.rs +++ b/stacks-signer/src/cli.rs @@ -340,14 +340,14 @@ pub fn parse_pox_addr(pox_address_literal: &str) -> Result { Ok, ); match parsed_addr { - Ok(PoxAddress::Standard(addr, None)) => match addr.version { + Ok(PoxAddress::Standard(addr, None)) => match addr.version() { C32_ADDRESS_VERSION_MAINNET_MULTISIG | C32_ADDRESS_VERSION_TESTNET_MULTISIG => Ok( PoxAddress::Standard(addr, Some(AddressHashMode::SerializeP2SH)), ), C32_ADDRESS_VERSION_MAINNET_SINGLESIG | C32_ADDRESS_VERSION_TESTNET_SINGLESIG => Ok( PoxAddress::Standard(addr, Some(AddressHashMode::SerializeP2PKH)), ), - _ => Err(format!("Invalid address version: {}", addr.version)), + _ => Err(format!("Invalid address version: {}", addr.version())), }, _ => parsed_addr, } @@ -451,7 +451,7 @@ mod tests { ); match pox_addr { PoxAddress::Standard(stacks_addr, hash_mode) => { - assert_eq!(stacks_addr.version, 22); + assert_eq!(stacks_addr.version(), 22); assert_eq!(hash_mode, Some(AddressHashMode::SerializeP2PKH)); } _ => panic!("Invalid parsed address"), @@ -467,7 +467,7 @@ mod tests { make_message_hash(&pox_addr); match pox_addr { PoxAddress::Standard(stacks_addr, hash_mode) => { - assert_eq!(stacks_addr.version, 20); + assert_eq!(stacks_addr.version(), 20); assert_eq!(hash_mode, Some(AddressHashMode::SerializeP2SH)); } _ => panic!("Invalid parsed address"), @@ -483,7 +483,7 @@ mod tests { make_message_hash(&pox_addr); match pox_addr { PoxAddress::Standard(stacks_addr, hash_mode) => { - assert_eq!(stacks_addr.version, C32_ADDRESS_VERSION_TESTNET_SINGLESIG); + assert_eq!(stacks_addr.version(), C32_ADDRESS_VERSION_TESTNET_SINGLESIG); assert_eq!(hash_mode, Some(AddressHashMode::SerializeP2PKH)); } _ => panic!("Invalid parsed address"), diff --git a/stacks-signer/src/v0/signer.rs b/stacks-signer/src/v0/signer.rs index dfd61ee35d..70253f8258 100644 --- a/stacks-signer/src/v0/signer.rs +++ b/stacks-signer/src/v0/signer.rs @@ -985,7 +985,7 @@ impl Signer { // authenticate the signature -- it must be signed by one of the stacking set let is_valid_sig = self.signer_addresses.iter().any(|addr| { // it only matters that the address hash bytes match - signer_address.bytes == addr.bytes + signer_address.bytes() == addr.bytes() }); if !is_valid_sig { @@ -1081,7 +1081,7 @@ impl Signer { let stacker_address = StacksAddress::p2pkh(self.mainnet, &public_key); // it only matters that the address hash bytes match - stacker_address.bytes == addr.bytes + stacker_address.bytes() == addr.bytes() }); if !is_valid_sig { diff --git a/stackslib/src/blockstack_cli.rs b/stackslib/src/blockstack_cli.rs index 7de42614a7..06ea43359f 100644 --- a/stackslib/src/blockstack_cli.rs +++ b/stackslib/src/blockstack_cli.rs @@ -633,7 +633,7 @@ fn get_addresses(args: &[String], version: TransactionVersion) -> Result TxOut { - let btc_version = to_b58_version_byte(addr.version) + let btc_version = to_b58_version_byte(addr.version()) .expect("BUG: failed to decode Stacks version byte to Bitcoin version byte"); let btc_addr_type = legacy_version_byte_to_address_type(btc_version) .expect("BUG: failed to decode Bitcoin version byte") .0; match btc_addr_type { LegacyBitcoinAddressType::PublicKeyHash => { - LegacyBitcoinAddress::to_p2pkh_tx_out(&addr.bytes, value) + LegacyBitcoinAddress::to_p2pkh_tx_out(addr.bytes(), value) } LegacyBitcoinAddressType::ScriptHash => { - LegacyBitcoinAddress::to_p2sh_tx_out(&addr.bytes, value) + LegacyBitcoinAddress::to_p2sh_tx_out(addr.bytes(), value) } } } @@ -1764,8 +1764,8 @@ mod tests { memo: vec![0x1f], commit_outs: vec![ - PoxAddress::Standard( StacksAddress { version: 26, bytes: Hash160::empty() }, None ), - PoxAddress::Standard( StacksAddress { version: 26, bytes: Hash160::empty() }, None ), + PoxAddress::Standard( StacksAddress::new(26, Hash160::empty()).unwrap(), None ), + PoxAddress::Standard( StacksAddress::new(26, Hash160::empty()).unwrap(), None ), ], burn_fee: 24690, @@ -3260,7 +3260,7 @@ mod tests { let anchor_block_hash = BlockHeaderHash([0xaa; 32]); fn reward_addrs(i: usize) -> PoxAddress { - let addr = StacksAddress::new(1, Hash160::from_data(&i.to_be_bytes())); + let addr = StacksAddress::new(1, Hash160::from_data(&i.to_be_bytes())).unwrap(); PoxAddress::Standard(addr, None) } let burn_addr_0 = PoxAddress::Standard(StacksAddress::burn_address(false), None); diff --git a/stackslib/src/chainstate/burn/operations/mod.rs b/stackslib/src/chainstate/burn/operations/mod.rs index 5688fa4983..3d032d4c8a 100644 --- a/stackslib/src/chainstate/burn/operations/mod.rs +++ b/stackslib/src/chainstate/burn/operations/mod.rs @@ -369,8 +369,8 @@ pub fn stacks_addr_serialize(addr: &StacksAddress) -> serde_json::Value { let addr_str = addr.to_string(); json!({ "address": addr_str, - "address_hash_bytes": format!("0x{}", addr.bytes), - "address_version": addr.version + "address_hash_bytes": format!("0x{}", addr.bytes()), + "address_version": addr.version() }) } diff --git a/stackslib/src/chainstate/burn/operations/stack_stx.rs b/stackslib/src/chainstate/burn/operations/stack_stx.rs index 05db7637ae..2ec23d89e6 100644 --- a/stackslib/src/chainstate/burn/operations/stack_stx.rs +++ b/stackslib/src/chainstate/burn/operations/stack_stx.rs @@ -507,10 +507,7 @@ mod tests { ], }; - let sender = StacksAddress { - version: 0, - bytes: Hash160([0; 20]), - }; + let sender = StacksAddress::new(0, Hash160([0; 20])).unwrap(); let op = PreStxOp::parse_from_tx( 16843022, &BurnchainHeaderHash([0; 32]), @@ -571,10 +568,7 @@ mod tests { ], }; - let sender = StacksAddress { - version: 0, - bytes: Hash160([0; 20]), - }; + let sender = StacksAddress::new(0, Hash160([0; 20])).unwrap(); // pre-2.1 this fails let op_err = PreStxOp::parse_from_tx( @@ -652,10 +646,7 @@ mod tests { ], }; - let sender = StacksAddress { - version: 0, - bytes: Hash160([0; 20]), - }; + let sender = StacksAddress::new(0, Hash160([0; 20])).unwrap(); let op = StackStxOp::parse_from_tx( 16843022, &BurnchainHeaderHash([0; 32]), @@ -726,10 +717,7 @@ mod tests { ], }; - let sender = StacksAddress { - version: 0, - bytes: Hash160([0; 20]), - }; + let sender = StacksAddress::new(0, Hash160([0; 20])).unwrap(); let op = StackStxOp::parse_from_tx( 16843022, &BurnchainHeaderHash([0; 32]), @@ -798,10 +786,7 @@ mod tests { ], }; - let sender = StacksAddress { - version: 0, - bytes: Hash160([0; 20]), - }; + let sender = StacksAddress::new(0, Hash160([0; 20])).unwrap(); // pre-2.1: this fails let op_err = StackStxOp::parse_from_tx( @@ -849,10 +834,7 @@ mod tests { let sender_addr = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2"; let sender = StacksAddress::from_string(sender_addr).unwrap(); let reward_addr = PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]), - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])).unwrap(), None, ); let op = StackStxOp { diff --git a/stackslib/src/chainstate/burn/operations/test/serialization.rs b/stackslib/src/chainstate/burn/operations/test/serialization.rs index cbc48f7e6e..b698ae4a6f 100644 --- a/stackslib/src/chainstate/burn/operations/test/serialization.rs +++ b/stackslib/src/chainstate/burn/operations/test/serialization.rs @@ -61,10 +61,7 @@ fn test_serialization_stack_stx_op() { let sender_addr = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2"; let sender = StacksAddress::from_string(sender_addr).unwrap(); let reward_addr = PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]), - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])).unwrap(), None, ); @@ -110,10 +107,7 @@ fn test_serialization_stack_stx_op_with_signer_key() { let sender_addr = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2"; let sender = StacksAddress::from_string(sender_addr).unwrap(); let reward_addr = PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]), - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])).unwrap(), None, ); @@ -191,10 +185,7 @@ fn test_serialization_delegate_stx_op() { let delegate_to_addr = "SP24ZBZ8ZE6F48JE9G3F3HRTG9FK7E2H6K2QZ3Q1K"; let delegate_to = StacksAddress::from_string(delegate_to_addr).unwrap(); let pox_addr = PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]), - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])).unwrap(), None, ); let op = DelegateStxOp { diff --git a/stackslib/src/chainstate/burn/operations/transfer_stx.rs b/stackslib/src/chainstate/burn/operations/transfer_stx.rs index b03cfe27b9..d8ff0d5da6 100644 --- a/stackslib/src/chainstate/burn/operations/transfer_stx.rs +++ b/stackslib/src/chainstate/burn/operations/transfer_stx.rs @@ -304,10 +304,7 @@ mod tests { ], }; - let sender = StacksAddress { - version: 0, - bytes: Hash160([0; 20]), - }; + let sender = StacksAddress::new(0, Hash160([0; 20])).unwrap(); let op = TransferStxOp::parse_from_tx( 16843022, &BurnchainHeaderHash([0; 32]), diff --git a/stackslib/src/chainstate/burn/operations/vote_for_aggregate_key.rs b/stackslib/src/chainstate/burn/operations/vote_for_aggregate_key.rs index 3750177a2c..7d7ec5e294 100644 --- a/stackslib/src/chainstate/burn/operations/vote_for_aggregate_key.rs +++ b/stackslib/src/chainstate/burn/operations/vote_for_aggregate_key.rs @@ -268,10 +268,7 @@ mod tests { }], }; - let sender = StacksAddress { - version: 0, - bytes: Hash160([0; 20]), - }; + let sender = StacksAddress::new(0, Hash160([0; 20])).unwrap(); let vote_op = VoteForAggregateKeyOp::parse_from_tx( 1000, &BurnchainHeaderHash([0; 32]), @@ -324,10 +321,7 @@ mod tests { }], }; - let sender = StacksAddress { - version: 0, - bytes: Hash160([0; 20]), - }; + let sender = StacksAddress::new(0, Hash160([0; 20])).unwrap(); let vote_op = VoteForAggregateKeyOp::parse_from_tx( 1000, &BurnchainHeaderHash([0; 32]), @@ -369,10 +363,7 @@ mod tests { }], }; - let sender = StacksAddress { - version: 0, - bytes: Hash160([0; 20]), - }; + let sender = StacksAddress::new(0, Hash160([0; 20])).unwrap(); let vote_op = VoteForAggregateKeyOp::parse_from_tx( 1000, &BurnchainHeaderHash([0; 32]), diff --git a/stackslib/src/chainstate/nakamoto/coordinator/tests.rs b/stackslib/src/chainstate/nakamoto/coordinator/tests.rs index e0b3375452..62ae7682b4 100644 --- a/stackslib/src/chainstate/nakamoto/coordinator/tests.rs +++ b/stackslib/src/chainstate/nakamoto/coordinator/tests.rs @@ -110,7 +110,7 @@ fn advance_to_nakamoto( ) .unwrap(); let default_pox_addr = - PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, addr.bytes.clone()); + PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, addr.bytes().clone()); let mut tip = None; for sortition_height in 0..11 { @@ -825,7 +825,8 @@ fn block_descendant() { StacksAddress::new( C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160::from_data(&index.to_be_bytes()), - ), + ) + .unwrap(), Some(AddressHashMode::SerializeP2PKH), )), }) @@ -914,7 +915,8 @@ fn block_info_tests(use_primary_testnet: bool) { StacksAddress::new( C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160::from_data(&index.to_be_bytes()), - ), + ) + .unwrap(), Some(AddressHashMode::SerializeP2PKH), )), max_amount: None, @@ -1342,7 +1344,8 @@ fn pox_treatment() { StacksAddress::new( C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160::from_data(&index.to_be_bytes()), - ), + ) + .unwrap(), Some(AddressHashMode::SerializeP2PKH), )), max_amount: None, @@ -3093,7 +3096,8 @@ fn process_next_nakamoto_block_deadlock() { StacksAddress::new( C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160::from_data(&index.to_be_bytes()), - ), + ) + .unwrap(), Some(AddressHashMode::SerializeP2PKH), )), max_amount: None, diff --git a/stackslib/src/chainstate/nakamoto/mod.rs b/stackslib/src/chainstate/nakamoto/mod.rs index 7584af67d3..e574af50c2 100644 --- a/stackslib/src/chainstate/nakamoto/mod.rs +++ b/stackslib/src/chainstate/nakamoto/mod.rs @@ -4807,10 +4807,10 @@ impl NakamotoChainState { .map(|hash160| // each miner gets two slots ( - StacksAddress { - version: 1, // NOTE: the version is ignored in stackerdb; we only care about the hashbytes - bytes: hash160 - }, + StacksAddress::new( + 1, // NOTE: the version is ignored in stackerdb; we only care about the hashbytes + hash160 + ).expect("FATAL: infallible: 1 is not a valid address version byte"), MINER_SLOT_COUNT, )) .collect(); diff --git a/stackslib/src/chainstate/nakamoto/test_signers.rs b/stackslib/src/chainstate/nakamoto/test_signers.rs index 7b5e35a0fd..4b63874aaf 100644 --- a/stackslib/src/chainstate/nakamoto/test_signers.rs +++ b/stackslib/src/chainstate/nakamoto/test_signers.rs @@ -165,10 +165,11 @@ impl TestSigners { weight: 1, }; let pox_addr = PoxAddress::Standard( - StacksAddress { - version: AddressHashMode::SerializeP2PKH.to_version_testnet(), - bytes: Hash160::from_data(&nakamoto_signer_entry.signing_key), - }, + StacksAddress::new( + AddressHashMode::SerializeP2PKH.to_version_testnet(), + Hash160::from_data(&nakamoto_signer_entry.signing_key), + ) + .expect("FATAL: constant testnet address version is not supported"), Some(AddressHashMode::SerializeP2PKH), ); signer_entries.push(nakamoto_signer_entry); diff --git a/stackslib/src/chainstate/nakamoto/tests/mod.rs b/stackslib/src/chainstate/nakamoto/tests/mod.rs index 38e7d99338..77d2e7d4af 100644 --- a/stackslib/src/chainstate/nakamoto/tests/mod.rs +++ b/stackslib/src/chainstate/nakamoto/tests/mod.rs @@ -2063,10 +2063,7 @@ fn test_make_miners_stackerdb_config() { .collect(); let miner_addrs: Vec<_> = miner_hash160s .iter() - .map(|miner_hash160| StacksAddress { - version: 1, - bytes: miner_hash160.clone(), - }) + .map(|miner_hash160| StacksAddress::new(1, miner_hash160.clone()).unwrap()) .collect(); debug!("miners = {:#?}", &miner_hash160s); @@ -2268,8 +2265,8 @@ fn test_make_miners_stackerdb_config() { .iter() .map(|config| { ( - config.signers[0].0.bytes.clone(), - config.signers[1].0.bytes.clone(), + config.signers[0].0.bytes().clone(), + config.signers[1].0.bytes().clone(), ) }) .collect(); diff --git a/stackslib/src/chainstate/nakamoto/tests/node.rs b/stackslib/src/chainstate/nakamoto/tests/node.rs index e9bdb4847b..b831cc4d61 100644 --- a/stackslib/src/chainstate/nakamoto/tests/node.rs +++ b/stackslib/src/chainstate/nakamoto/tests/node.rs @@ -149,7 +149,7 @@ impl TestStacker { let pox_key = StacksPrivateKey::from_seed(&[*key_seed, *key_seed]); let addr = StacksAddress::p2pkh(false, &StacksPublicKey::from_private(&pox_key)); let pox_addr = - PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, addr.bytes.clone()); + PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, addr.bytes().clone()); TestStacker { signer_private_key: signing_key.clone(), diff --git a/stackslib/src/chainstate/stacks/address.rs b/stackslib/src/chainstate/stacks/address.rs index c97f535e4d..6ba35d7207 100644 --- a/stackslib/src/chainstate/stacks/address.rs +++ b/stackslib/src/chainstate/stacks/address.rs @@ -131,7 +131,7 @@ impl PoxAddress { #[cfg(any(test, feature = "testing"))] pub fn hash160(&self) -> Hash160 { match *self { - PoxAddress::Standard(addr, _) => addr.bytes.clone(), + PoxAddress::Standard(addr, _) => addr.bytes().clone(), _ => panic!("Called hash160 on a non-standard PoX address"), } } @@ -140,7 +140,7 @@ impl PoxAddress { /// version. pub fn bytes(&self) -> Vec { match *self { - PoxAddress::Standard(addr, _) => addr.bytes.0.to_vec(), + PoxAddress::Standard(addr, _) => addr.bytes().0.to_vec(), PoxAddress::Addr20(_, _, bytes) => bytes.to_vec(), PoxAddress::Addr32(_, _, bytes) => bytes.to_vec(), } @@ -171,7 +171,7 @@ impl PoxAddress { }; Some(PoxAddress::Standard( - StacksAddress { version, bytes }, + StacksAddress::new(version, bytes).ok()?, Some(hashmode), )) } @@ -293,7 +293,7 @@ impl PoxAddress { pub fn to_burnchain_repr(&self) -> String { match *self { PoxAddress::Standard(ref addr, _) => { - format!("{:02x}-{}", &addr.version, &addr.bytes) + format!("{:02x}-{}", &addr.version(), &addr.bytes()) } PoxAddress::Addr20(_, ref addrtype, ref addrbytes) => { format!("{:02x}-{}", addrtype.to_u8(), to_hex(addrbytes)) @@ -328,7 +328,7 @@ impl PoxAddress { } }; let version = Value::buff_from_byte(*hm as u8); - let hashbytes = Value::buff_from(Vec::from(addr.bytes.0.clone())) + let hashbytes = Value::buff_from(Vec::from(addr.bytes().0.clone())) .expect("FATAL: hash160 does not fit into a Clarity value"); let tuple_data = TupleData::from_data(vec![ @@ -376,7 +376,7 @@ impl PoxAddress { pub fn coerce_hash_mode(self) -> PoxAddress { match self { PoxAddress::Standard(addr, _) => { - let hm = AddressHashMode::from_version(addr.version); + let hm = AddressHashMode::from_version(addr.version()); PoxAddress::Standard(addr, Some(hm)) } _ => self, @@ -429,7 +429,7 @@ impl PoxAddress { match *self { PoxAddress::Standard(addr, _) => { // legacy Bitcoin address - let btc_version = to_b58_version_byte(addr.version).expect( + let btc_version = to_b58_version_byte(addr.version()).expect( "BUG: failed to decode Stacks version byte to legacy Bitcoin version byte", ); let btc_addr_type = legacy_version_byte_to_address_type(btc_version) @@ -437,10 +437,10 @@ impl PoxAddress { .0; match btc_addr_type { LegacyBitcoinAddressType::PublicKeyHash => { - LegacyBitcoinAddress::to_p2pkh_tx_out(&addr.bytes, value) + LegacyBitcoinAddress::to_p2pkh_tx_out(addr.bytes(), value) } LegacyBitcoinAddressType::ScriptHash => { - LegacyBitcoinAddress::to_p2sh_tx_out(&addr.bytes, value) + LegacyBitcoinAddress::to_p2sh_tx_out(addr.bytes(), value) } } } @@ -500,10 +500,7 @@ impl PoxAddress { #[cfg(any(test, feature = "testing"))] pub fn from_legacy(hash_mode: AddressHashMode, hash_bytes: Hash160) -> PoxAddress { PoxAddress::Standard( - StacksAddress { - version: hash_mode.to_version_testnet(), - bytes: hash_bytes, - }, + StacksAddress::new(hash_mode.to_version_testnet(), hash_bytes).unwrap(), Some(hash_mode), ) } @@ -524,14 +521,12 @@ impl StacksAddressExtensions for StacksAddress { // should not fail by construction let version = to_c32_version_byte(btc_version) .expect("Failed to decode Bitcoin version byte to Stacks version byte"); - StacksAddress { - version, - bytes: addr.bytes.clone(), - } + StacksAddress::new(version, addr.bytes.clone()) + .expect("FATAL: failed to convert bitcoin address type to stacks address version byte") } fn to_b58(self) -> String { - let StacksAddress { version, bytes } = self; + let (version, bytes) = self.destruct(); let btc_version = to_b58_version_byte(version) // fallback to version .unwrap_or(version); @@ -556,10 +551,7 @@ mod test { #[test] fn tx_stacks_address_codec() { - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let addr_bytes = [ // version 0x01, // bytes @@ -574,7 +566,7 @@ mod test { fn tx_stacks_address_valid_p2pkh() { // p2pkh should accept compressed or uncompressed assert_eq!(StacksAddress::from_public_keys(1, &AddressHashMode::SerializeP2PKH, 1, &vec![PubKey::from_hex("04b7c7cbe36a1aed38c6324b143584a1e822bbf0c4435b102f0497ccb592baf8e964a5a270f9348285595b78855c3e33dc36708e34f9abdeeaad4d2977cb81e3a1").unwrap()]), - Some(StacksAddress { version: 1, bytes: Hash160::from_hex("560ee9d7f5694dd4dbeddf55eff16bcc05409fef").unwrap() })); + Some(StacksAddress::new(1, Hash160::from_hex("560ee9d7f5694dd4dbeddf55eff16bcc05409fef").unwrap()).unwrap())); assert_eq!( StacksAddress::from_public_keys( @@ -586,10 +578,13 @@ mod test { ) .unwrap()] ), - Some(StacksAddress { - version: 2, - bytes: Hash160::from_hex("e3771b5724d9a8daca46052bab5d0f533cd1e619").unwrap() - }) + Some( + StacksAddress::new( + 2, + Hash160::from_hex("e3771b5724d9a8daca46052bab5d0f533cd1e619").unwrap() + ) + .unwrap() + ) ); // should fail if we have too many signatures @@ -623,10 +618,13 @@ mod test { ) .unwrap()] ), - Some(StacksAddress { - version: 4, - bytes: Hash160::from_hex("384d172898686fd0337fba27843add64cbe684f1").unwrap() - }) + Some( + StacksAddress::new( + 4, + Hash160::from_hex("384d172898686fd0337fba27843add64cbe684f1").unwrap() + ) + .unwrap() + ) ); } @@ -653,16 +651,19 @@ mod test { .unwrap() ] ), - Some(StacksAddress { - version: 5, - bytes: Hash160::from_hex("b01162ecda72c57ed419f7966ec4e8dd7987c704").unwrap() - }) + Some( + StacksAddress::new( + 5, + Hash160::from_hex("b01162ecda72c57ed419f7966ec4e8dd7987c704").unwrap() + ) + .unwrap() + ) ); assert_eq!(StacksAddress::from_public_keys(6, &AddressHashMode::SerializeP2SH, 2, &vec![PubKey::from_hex("04b30fafab3a12372c5d150d567034f37d60a91168009a779498168b0e9d8ec7f259fc6bc2f317febe245344d9e11912427cee095b64418719207ac502e8cff0ce").unwrap(), PubKey::from_hex("04ce61f1d155738a5e434fc8a61c3e104f891d1ec71576e8ad85abb68b34670d35c61aec8a973b3b7d68c7325b03c1d18a82e88998b8307afeaa491c1e45e46255").unwrap(), PubKey::from_hex("04ef2340518b5867b23598a9cf74611f8b98064f7d55cdb8c107c67b5efcbc5c771f112f919b00a6c6c5f51f7c63e1762fe9fac9b66ec75a053db7f51f4a52712b").unwrap()]), - Some(StacksAddress { version: 6, bytes: Hash160::from_hex("1003ab7fc0ba18a343da2818c560109c170cdcbb").unwrap() })); + Some(StacksAddress::new(6, Hash160::from_hex("1003ab7fc0ba18a343da2818c560109c170cdcbb").unwrap()).unwrap())); } #[test] @@ -688,10 +689,13 @@ mod test { .unwrap() ] ), - Some(StacksAddress { - version: 7, - bytes: Hash160::from_hex("57130f08a480e7518c1d685e8bb88008d90a0a60").unwrap() - }) + Some( + StacksAddress::new( + 7, + Hash160::from_hex("57130f08a480e7518c1d685e8bb88008d90a0a60").unwrap() + ) + .unwrap() + ) ); assert_eq!(StacksAddress::from_public_keys(8, &AddressHashMode::SerializeP2PKH, 2, &vec![PubKey::from_hex("04b30fafab3a12372c5d150d567034f37d60a91168009a779498168b0e9d8ec7f259fc6bc2f317febe245344d9e11912427cee095b64418719207ac502e8cff0ce").unwrap(), @@ -721,10 +725,8 @@ mod test { assert_eq!( PoxAddress::try_from_pox_tuple(true, &make_pox_addr_raw(0x00, vec![0x01; 20])).unwrap(), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2PKH) ) ); @@ -732,20 +734,16 @@ mod test { PoxAddress::try_from_pox_tuple(false, &make_pox_addr_raw(0x00, vec![0x02; 20])) .unwrap(), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_SINGLESIG, - bytes: Hash160([0x02; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160([0x02; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2PKH) ) ); assert_eq!( PoxAddress::try_from_pox_tuple(true, &make_pox_addr_raw(0x01, vec![0x03; 20])).unwrap(), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x03; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x03; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2SH) ) ); @@ -753,20 +751,16 @@ mod test { PoxAddress::try_from_pox_tuple(false, &make_pox_addr_raw(0x01, vec![0x04; 20])) .unwrap(), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: Hash160([0x04; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, Hash160([0x04; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2SH) ) ); assert_eq!( PoxAddress::try_from_pox_tuple(true, &make_pox_addr_raw(0x02, vec![0x05; 20])).unwrap(), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x05; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x05; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2WPKH) ) ); @@ -774,20 +768,16 @@ mod test { PoxAddress::try_from_pox_tuple(false, &make_pox_addr_raw(0x02, vec![0x06; 20])) .unwrap(), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: Hash160([0x06; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, Hash160([0x06; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2WPKH) ) ); assert_eq!( PoxAddress::try_from_pox_tuple(true, &make_pox_addr_raw(0x03, vec![0x07; 20])).unwrap(), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x07; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x07; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2WSH) ) ); @@ -795,10 +785,8 @@ mod test { PoxAddress::try_from_pox_tuple(false, &make_pox_addr_raw(0x03, vec![0x08; 20])) .unwrap(), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: Hash160([0x08; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, Hash160([0x08; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2WSH) ) ); @@ -943,10 +931,8 @@ mod test { fn test_as_clarity_tuple() { assert_eq!( PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2PKH) ) .as_clarity_tuple() @@ -957,10 +943,8 @@ mod test { ); assert_eq!( PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_SINGLESIG, - bytes: Hash160([0x02; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160([0x02; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2PKH) ) .as_clarity_tuple() @@ -970,19 +954,13 @@ mod test { .unwrap() ); assert!(PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])).unwrap(), None ) .as_clarity_tuple() .is_none()); assert!(PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_SINGLESIG, - bytes: Hash160([0x02; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160([0x02; 20])).unwrap(), None ) .as_clarity_tuple() @@ -990,10 +968,8 @@ mod test { assert_eq!( PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2SH) ) .as_clarity_tuple() @@ -1004,10 +980,8 @@ mod test { ); assert_eq!( PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: Hash160([0x02; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, Hash160([0x02; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2SH) ) .as_clarity_tuple() @@ -1017,19 +991,13 @@ mod test { .unwrap() ); assert!(PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])).unwrap(), None ) .as_clarity_tuple() .is_none()); assert!(PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: Hash160([0x02; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, Hash160([0x02; 20])).unwrap(), None ) .as_clarity_tuple() @@ -1037,10 +1005,8 @@ mod test { assert_eq!( PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2WPKH) ) .as_clarity_tuple() @@ -1051,10 +1017,8 @@ mod test { ); assert_eq!( PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: Hash160([0x02; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, Hash160([0x02; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2WPKH) ) .as_clarity_tuple() @@ -1064,19 +1028,13 @@ mod test { .unwrap() ); assert!(PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])).unwrap(), None ) .as_clarity_tuple() .is_none()); assert!(PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: Hash160([0x02; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, Hash160([0x02; 20])).unwrap(), None ) .as_clarity_tuple() @@ -1084,10 +1042,8 @@ mod test { assert_eq!( PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2WSH) ) .as_clarity_tuple() @@ -1098,10 +1054,8 @@ mod test { ); assert_eq!( PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: Hash160([0x02; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, Hash160([0x02; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2WSH) ) .as_clarity_tuple() @@ -1111,19 +1065,13 @@ mod test { .unwrap() ); assert!(PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])).unwrap(), None ) .as_clarity_tuple() .is_none()); assert!(PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: Hash160([0x02; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, Hash160([0x02; 20])).unwrap(), None ) .as_clarity_tuple() @@ -1185,10 +1133,8 @@ mod test { fn test_to_bitcoin_tx_out() { assert_eq!( PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2PKH) ) .to_bitcoin_tx_out(123) @@ -1198,10 +1144,8 @@ mod test { ); assert_eq!( PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2PKH) ) .to_bitcoin_tx_out(123) @@ -1239,10 +1183,8 @@ mod test { // representative test PoxAddresses let pox_addrs: Vec = vec![ PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]), - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2PKH), ), PoxAddress::Addr20(true, PoxAddressType20::P2WPKH, [0x01; 20]), @@ -1252,31 +1194,23 @@ mod test { PoxAddress::Addr32(true, PoxAddressType32::P2TR, [0x01; 32]), PoxAddress::Addr32(false, PoxAddressType32::P2TR, [0x01; 32]), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]), - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2SH), ), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]), - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2SH), ), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]), - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2WSH), ), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]), - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])) + .unwrap(), Some(AddressHashMode::SerializeP2WPKH), ), ]; @@ -1304,10 +1238,8 @@ mod test { }) .unwrap(), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_SINGLESIG, Hash160([0x01; 20])) + .unwrap(), None ) ); @@ -1322,10 +1254,8 @@ mod test { }) .unwrap(), PoxAddress::Standard( - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160([0x01; 20]) - }, + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, Hash160([0x01; 20])) + .unwrap(), None ) ); diff --git a/stackslib/src/chainstate/stacks/auth.rs b/stackslib/src/chainstate/stacks/auth.rs index 4f644bbdcc..b54d494226 100644 --- a/stackslib/src/chainstate/stacks/auth.rs +++ b/stackslib/src/chainstate/stacks/auth.rs @@ -222,17 +222,13 @@ impl MultisigSpendingCondition { } pub fn address_mainnet(&self) -> StacksAddress { - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: self.signer.clone(), - } + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, self.signer.clone()) + .expect("FATAL: infallible: constant is not a valid address byte") } pub fn address_testnet(&self) -> StacksAddress { - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: self.signer.clone(), - } + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, self.signer.clone()) + .expect("FATAL: infallible: constant is not a valid address byte") } /// Authenticate a spending condition against an initial sighash. @@ -290,24 +286,21 @@ impl MultisigSpendingCondition { )); } - let addr_bytes = match StacksAddress::from_public_keys( + let addr = StacksAddress::from_public_keys( 0, &self.hash_mode.to_address_hash_mode(), self.signatures_required as usize, &pubkeys, - ) { - Some(a) => a.bytes, - None => { - return Err(net_error::VerifyingError( - "Failed to generate address from public keys".to_string(), - )); - } - }; + ) + .ok_or_else(|| { + net_error::VerifyingError("Failed to generate address from public keys".to_string()) + })?; - if addr_bytes != self.signer { + if *addr.bytes() != self.signer { return Err(net_error::VerifyingError(format!( "Signer hash does not equal hash of public key(s): {} != {}", - addr_bytes, self.signer + addr.bytes(), + self.signer ))); } @@ -419,17 +412,13 @@ impl OrderIndependentMultisigSpendingCondition { } pub fn address_mainnet(&self) -> StacksAddress { - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: self.signer.clone(), - } + StacksAddress::new(C32_ADDRESS_VERSION_MAINNET_MULTISIG, self.signer.clone()) + .expect("FATAL: infallible: constant address byte is not supported") } pub fn address_testnet(&self) -> StacksAddress { - StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_MULTISIG, - bytes: self.signer.clone(), - } + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_MULTISIG, self.signer.clone()) + .expect("FATAL: infallible: constant address byte is not supported") } /// Authenticate a spending condition against an initial sighash. @@ -486,24 +475,21 @@ impl OrderIndependentMultisigSpendingCondition { )); } - let addr_bytes = match StacksAddress::from_public_keys( + let addr = StacksAddress::from_public_keys( 0, &self.hash_mode.to_address_hash_mode(), self.signatures_required as usize, &pubkeys, - ) { - Some(a) => a.bytes, - None => { - return Err(net_error::VerifyingError( - "Failed to generate address from public keys".to_string(), - )); - } - }; + ) + .ok_or_else(|| { + net_error::VerifyingError("Failed to generate address from public keys".to_string()) + })?; - if addr_bytes != self.signer { + if *addr.bytes() != self.signer { return Err(net_error::VerifyingError(format!( "Signer hash does not equal hash of public key(s): {} != {}", - addr_bytes, self.signer + addr.bytes(), + self.signer ))); } @@ -590,10 +576,8 @@ impl SinglesigSpendingCondition { SinglesigHashMode::P2PKH => C32_ADDRESS_VERSION_MAINNET_SINGLESIG, SinglesigHashMode::P2WPKH => C32_ADDRESS_VERSION_MAINNET_MULTISIG, }; - StacksAddress { - version, - bytes: self.signer.clone(), - } + StacksAddress::new(version, self.signer.clone()) + .expect("FATAL: infallible: supported address constant is not valid") } pub fn address_testnet(&self) -> StacksAddress { @@ -601,10 +585,8 @@ impl SinglesigSpendingCondition { SinglesigHashMode::P2PKH => C32_ADDRESS_VERSION_TESTNET_SINGLESIG, SinglesigHashMode::P2WPKH => C32_ADDRESS_VERSION_TESTNET_MULTISIG, }; - StacksAddress { - version, - bytes: self.signer.clone(), - } + StacksAddress::new(version, self.signer.clone()) + .expect("FATAL: infallible: supported address constant is not valid") } /// Authenticate a spending condition against an initial sighash. @@ -624,24 +606,22 @@ impl SinglesigSpendingCondition { &self.key_encoding, &self.signature, )?; - let addr_bytes = match StacksAddress::from_public_keys( + + let addr = StacksAddress::from_public_keys( 0, &self.hash_mode.to_address_hash_mode(), 1, &vec![pubkey], - ) { - Some(a) => a.bytes, - None => { - return Err(net_error::VerifyingError( - "Failed to generate address from public key".to_string(), - )); - } - }; + ) + .ok_or_else(|| { + net_error::VerifyingError("Failed to generate address from public key".to_string()) + })?; - if addr_bytes != self.signer { + if *addr.bytes() != self.signer { return Err(net_error::VerifyingError(format!( "Signer hash does not equal hash of public key(s): {} != {}", - &addr_bytes, &self.signer + addr.bytes(), + &self.signer ))); } @@ -708,7 +688,7 @@ impl TransactionSpendingCondition { Some(TransactionSpendingCondition::Singlesig( SinglesigSpendingCondition { - signer: signer_addr.bytes, + signer: signer_addr.destruct().1, nonce: 0, tx_fee: 0, hash_mode: SinglesigHashMode::P2PKH, @@ -728,7 +708,7 @@ impl TransactionSpendingCondition { Some(TransactionSpendingCondition::Singlesig( SinglesigSpendingCondition { - signer: signer_addr.bytes, + signer: signer_addr.destruct().1, nonce: 0, tx_fee: 0, hash_mode: SinglesigHashMode::P2WPKH, @@ -751,7 +731,7 @@ impl TransactionSpendingCondition { Some(TransactionSpendingCondition::Multisig( MultisigSpendingCondition { - signer: signer_addr.bytes, + signer: signer_addr.destruct().1, nonce: 0, tx_fee: 0, hash_mode: MultisigHashMode::P2SH, @@ -774,7 +754,7 @@ impl TransactionSpendingCondition { Some(TransactionSpendingCondition::OrderIndependentMultisig( OrderIndependentMultisigSpendingCondition { - signer: signer_addr.bytes, + signer: signer_addr.destruct().1, nonce: 0, tx_fee: 0, hash_mode: OrderIndependentMultisigHashMode::P2SH, @@ -797,7 +777,7 @@ impl TransactionSpendingCondition { Some(TransactionSpendingCondition::OrderIndependentMultisig( OrderIndependentMultisigSpendingCondition { - signer: signer_addr.bytes, + signer: signer_addr.destruct().1, nonce: 0, tx_fee: 0, hash_mode: OrderIndependentMultisigHashMode::P2WSH, @@ -820,7 +800,7 @@ impl TransactionSpendingCondition { Some(TransactionSpendingCondition::Multisig( MultisigSpendingCondition { - signer: signer_addr.bytes, + signer: signer_addr.destruct().1, nonce: 0, tx_fee: 0, hash_mode: MultisigHashMode::P2WSH, diff --git a/stackslib/src/chainstate/stacks/block.rs b/stackslib/src/chainstate/stacks/block.rs index a335e21894..bbdfda122b 100644 --- a/stackslib/src/chainstate/stacks/block.rs +++ b/stackslib/src/chainstate/stacks/block.rs @@ -1466,10 +1466,7 @@ mod test { let mut tx_invalid_coinbase = tx_coinbase.clone(); tx_invalid_coinbase.anchor_mode = TransactionAnchorMode::OffChainOnly; - let stx_address = StacksAddress { - version: 0, - bytes: Hash160([0u8; 20]), - }; + let stx_address = StacksAddress::new(0, Hash160([0u8; 20])).unwrap(); let mut tx_invalid_anchor = StacksTransaction::new( TransactionVersion::Testnet, origin_auth.clone(), @@ -1594,10 +1591,7 @@ mod test { let mut tx_coinbase_offchain = tx_coinbase.clone(); tx_coinbase_offchain.anchor_mode = TransactionAnchorMode::OffChainOnly; - let stx_address = StacksAddress { - version: 0, - bytes: Hash160([0u8; 20]), - }; + let stx_address = StacksAddress::new(0, Hash160([0u8; 20])).unwrap(); let mut tx_invalid_anchor = StacksTransaction::new( TransactionVersion::Testnet, origin_auth.clone(), @@ -1803,10 +1797,7 @@ mod test { microblock_pubkey_hash: Hash160([9u8; 20]), }; - let stx_address = StacksAddress { - version: 0, - bytes: Hash160([0u8; 20]), - }; + let stx_address = StacksAddress::new(0, Hash160([0u8; 20])).unwrap(); let privk = StacksPrivateKey::from_hex( "6d430bb91222408e7706c9001cfaeb91b08c2be6d5ac95779ab52c6b431950e001", @@ -1973,10 +1964,7 @@ mod test { TransactionPayload::Coinbase(CoinbasePayload([0u8; 32]), None, Some(proof)), ); - let stx_address = StacksAddress { - version: 0, - bytes: Hash160([0u8; 20]), - }; + let stx_address = StacksAddress::new(0, Hash160([0u8; 20])).unwrap(); let tx_transfer = StacksTransaction::new( TransactionVersion::Testnet, origin_auth.clone(), diff --git a/stackslib/src/chainstate/stacks/boot/contract_tests.rs b/stackslib/src/chainstate/stacks/boot/contract_tests.rs index 2fb95a5ace..8ca8a05006 100644 --- a/stackslib/src/chainstate/stacks/boot/contract_tests.rs +++ b/stackslib/src/chainstate/stacks/boot/contract_tests.rs @@ -1790,10 +1790,8 @@ fn test_deploy_smart_contract( fn max_stackerdb_list() { let signers_list: Vec<_> = (0..SIGNERS_MAX_LIST_SIZE) .map(|signer_ix| { - let signer_address = StacksAddress { - version: 0, - bytes: Hash160::from_data(&signer_ix.to_be_bytes()), - }; + let signer_address = + StacksAddress::new(0, Hash160::from_data(&signer_ix.to_be_bytes())).unwrap(); Value::Tuple( TupleData::from_data(vec![ ( diff --git a/stackslib/src/chainstate/stacks/boot/mod.rs b/stackslib/src/chainstate/stacks/boot/mod.rs index d4319d8a0f..20c2ae8168 100644 --- a/stackslib/src/chainstate/stacks/boot/mod.rs +++ b/stackslib/src/chainstate/stacks/boot/mod.rs @@ -2464,7 +2464,7 @@ pub mod test { make_tx(sender_key, nonce, 0, payload) } - fn make_tx( + pub fn make_tx( key: &StacksPrivateKey, nonce: u64, tx_fee: u64, @@ -3031,7 +3031,7 @@ pub mod test { ]; if tenure_id == 1 { - let alice_lockup_1 = make_pox_lockup(&alice, 0, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, key_to_stacks_addr(&alice).bytes, 1, tip.block_height); + let alice_lockup_1 = make_pox_lockup(&alice, 0, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, key_to_stacks_addr(&alice).destruct().1, 1, tip.block_height); block_txs.push(alice_lockup_1); } if tenure_id == 2 { @@ -3269,7 +3269,7 @@ pub mod test { 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 12, tip.block_height, ); @@ -3409,7 +3409,7 @@ pub mod test { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[0].1, 1024 * POX_THRESHOLD_STEPS_USTX); @@ -3485,7 +3485,7 @@ pub mod test { 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(key).bytes, + key_to_stacks_addr(key).destruct().1, 12, tip.block_height, ); @@ -3653,7 +3653,7 @@ pub mod test { assert_eq!(reward_addrs.len(), 4); let mut all_addrbytes = HashSet::new(); for key in keys.iter() { - all_addrbytes.insert(key_to_stacks_addr(&key).bytes); + all_addrbytes.insert(key_to_stacks_addr(&key).destruct().1); } for key in keys.iter() { @@ -3665,8 +3665,8 @@ pub mod test { (reward_addrs[0].0).version(), AddressHashMode::SerializeP2PKH as u8 ); - assert!(all_addrbytes.contains(&key_to_stacks_addr(&key).bytes)); - all_addrbytes.remove(&key_to_stacks_addr(&key).bytes); + assert!(all_addrbytes.contains(&key_to_stacks_addr(&key).destruct().1)); + all_addrbytes.remove(&key_to_stacks_addr(&key).destruct().1); assert_eq!(reward_addrs[0].1, 1024 * POX_THRESHOLD_STEPS_USTX); // Lock-up is consistent with stacker state @@ -3746,7 +3746,7 @@ pub mod test { "do-lockup", 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 1, ); block_txs.push(alice_stack); @@ -3899,7 +3899,7 @@ pub mod test { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[0].1, 1024 * POX_THRESHOLD_STEPS_USTX); @@ -4008,7 +4008,7 @@ pub mod test { 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 12, tip.block_height, ); @@ -4020,7 +4020,7 @@ pub mod test { 0, (4 * 1024 * POX_THRESHOLD_STEPS_USTX) / 5, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, 12, tip.block_height, ); @@ -4156,7 +4156,7 @@ pub mod test { ); assert_eq!( (reward_addrs[1].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[1].1, 1024 * POX_THRESHOLD_STEPS_USTX); @@ -4166,7 +4166,7 @@ pub mod test { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&bob).bytes + key_to_stacks_addr(&bob).destruct().1, ); assert_eq!(reward_addrs[0].1, (4 * 1024 * POX_THRESHOLD_STEPS_USTX) / 5); } else { @@ -4216,11 +4216,11 @@ pub mod test { if tenure_id == 1 { // Alice locks up exactly 12.5% of the liquid STX supply, twice. // Only the first one succeeds. - let alice_lockup_1 = make_pox_lockup(&alice, 0, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, key_to_stacks_addr(&alice).bytes, 12, tip.block_height); + let alice_lockup_1 = make_pox_lockup(&alice, 0, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, key_to_stacks_addr(&alice).destruct().1, 12, tip.block_height); block_txs.push(alice_lockup_1); // will be rejected - let alice_lockup_2 = make_pox_lockup(&alice, 1, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, key_to_stacks_addr(&alice).bytes, 12, tip.block_height); + let alice_lockup_2 = make_pox_lockup(&alice, 1, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, key_to_stacks_addr(&alice).destruct().1, 12, tip.block_height); block_txs.push(alice_lockup_2); // let's make some allowances for contract-calls through smart contracts @@ -4437,7 +4437,7 @@ pub mod test { 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 1, tip.block_height, ); @@ -4570,7 +4570,7 @@ pub mod test { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[0].1, 1024 * POX_THRESHOLD_STEPS_USTX); @@ -4686,7 +4686,7 @@ pub mod test { 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 1, tip.block_height, ); @@ -4703,7 +4703,7 @@ pub mod test { "do-lockup", 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&charlie).bytes, + key_to_stacks_addr(&charlie).destruct().1, 1, ); block_txs.push(charlie_stack); @@ -4723,7 +4723,7 @@ pub mod test { 1, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 1, tip.block_height, ); @@ -4737,7 +4737,7 @@ pub mod test { "do-lockup", 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&charlie).bytes, + key_to_stacks_addr(&charlie).destruct().1, 1, ); block_txs.push(charlie_stack); @@ -4907,7 +4907,7 @@ pub mod test { ); assert_eq!( (reward_addrs[1].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[1].1, 1024 * POX_THRESHOLD_STEPS_USTX); @@ -4917,7 +4917,7 @@ pub mod test { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&charlie).bytes + key_to_stacks_addr(&charlie).destruct().1, ); assert_eq!(reward_addrs[0].1, 1024 * POX_THRESHOLD_STEPS_USTX); @@ -5035,7 +5035,7 @@ pub mod test { ); assert_eq!( (reward_addrs[1].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[1].1, 512 * POX_THRESHOLD_STEPS_USTX); @@ -5045,7 +5045,7 @@ pub mod test { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&charlie).bytes + key_to_stacks_addr(&charlie).destruct().1, ); assert_eq!(reward_addrs[0].1, 512 * POX_THRESHOLD_STEPS_USTX); @@ -5208,7 +5208,7 @@ pub mod test { 0, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 1, tip.block_height, ); @@ -5219,7 +5219,7 @@ pub mod test { 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, 1, tip.block_height, ); @@ -5230,7 +5230,7 @@ pub mod test { 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&charlie).bytes, + key_to_stacks_addr(&charlie).destruct().1, 1, tip.block_height, ); @@ -5241,7 +5241,7 @@ pub mod test { 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&danielle).bytes, + key_to_stacks_addr(&danielle).destruct().1, 1, tip.block_height, ); @@ -5257,7 +5257,7 @@ pub mod test { "do-lockup", 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2SH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 1, ); block_txs.push(alice_stack); @@ -5367,23 +5367,23 @@ pub mod test { let expected_pox_addrs: Vec<(u8, Hash160)> = vec![ ( AddressHashMode::SerializeP2PKH as u8, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), ( AddressHashMode::SerializeP2PKH as u8, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), ( AddressHashMode::SerializeP2PKH as u8, - key_to_stacks_addr(&charlie).bytes, + key_to_stacks_addr(&charlie).destruct().1, ), ( AddressHashMode::SerializeP2PKH as u8, - key_to_stacks_addr(&danielle).bytes, + key_to_stacks_addr(&danielle).destruct().1, ), ( AddressHashMode::SerializeP2SH as u8, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), ]; @@ -5645,7 +5645,7 @@ pub mod test { if tenure_id == 1 { // Alice locks up exactly 25% of the liquid STX supply, so this should succeed. - let alice_lockup = make_pox_lockup(&alice, 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, key_to_stacks_addr(&alice).bytes, 12, tip.block_height); + let alice_lockup = make_pox_lockup(&alice, 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, key_to_stacks_addr(&alice).destruct().1, 12, tip.block_height); block_txs.push(alice_lockup); // Bob rejects with exactly 25% of the liquid STX supply (shouldn't affect @@ -5851,7 +5851,7 @@ pub mod test { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[0].1, 1024 * POX_THRESHOLD_STEPS_USTX); } diff --git a/stackslib/src/chainstate/stacks/boot/pox_2_tests.rs b/stackslib/src/chainstate/stacks/boot/pox_2_tests.rs index 3313e80c7f..d6e6795b8b 100644 --- a/stackslib/src/chainstate/stacks/boot/pox_2_tests.rs +++ b/stackslib/src/chainstate/stacks/boot/pox_2_tests.rs @@ -775,7 +775,7 @@ fn test_simple_pox_lockup_transition_pox_2() { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1 ); assert_eq!(reward_addrs[0].1, 1024 * POX_THRESHOLD_STEPS_USTX); } else { @@ -787,7 +787,7 @@ fn test_simple_pox_lockup_transition_pox_2() { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&bob).bytes + key_to_stacks_addr(&bob).destruct().1 ); assert_eq!(reward_addrs[0].1, 512 * POX_THRESHOLD_STEPS_USTX); @@ -797,7 +797,7 @@ fn test_simple_pox_lockup_transition_pox_2() { ); assert_eq!( (reward_addrs[1].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1 ); assert_eq!(reward_addrs[1].1, 512 * POX_THRESHOLD_STEPS_USTX); } @@ -828,7 +828,7 @@ fn test_simple_pox_lockup_transition_pox_2() { 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 4, tip.block_height, ); @@ -916,7 +916,7 @@ fn test_simple_pox_lockup_transition_pox_2() { 512 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 6, tip.block_height, @@ -939,7 +939,7 @@ fn test_simple_pox_lockup_transition_pox_2() { 1, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, 4, tip.block_height, ); @@ -971,7 +971,7 @@ fn test_simple_pox_lockup_transition_pox_2() { 512 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 12, tip.block_height, @@ -1001,7 +1001,7 @@ fn test_simple_pox_lockup_transition_pox_2() { 2, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 12, tip.block_height, ); @@ -1210,7 +1210,7 @@ fn test_simple_pox_2_auto_unlock(alice_first: bool) { 1024 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, tip.block_height, @@ -1222,7 +1222,7 @@ fn test_simple_pox_2_auto_unlock(alice_first: bool) { 1 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 6, tip.block_height, @@ -1246,11 +1246,11 @@ fn test_simple_pox_2_auto_unlock(alice_first: bool) { assert_eq!(reward_set_entries.len(), 2); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&bob).bytes.0.to_vec() + key_to_stacks_addr(&bob).bytes().0.to_vec() ); assert_eq!( reward_set_entries[1].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); } @@ -1285,7 +1285,7 @@ fn test_simple_pox_2_auto_unlock(alice_first: bool) { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); } @@ -1486,7 +1486,7 @@ fn delegate_stack_increase() { let bob = keys.pop().unwrap(); let bob_address = key_to_stacks_addr(&bob); let bob_principal = PrincipalData::from(bob_address.clone()); - let bob_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, bob_address.bytes.clone()); + let bob_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, bob_address.bytes().clone()); let mut alice_nonce = 0; let mut bob_nonce = 0; @@ -1866,7 +1866,7 @@ fn stack_increase() { first_lockup_amt, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, tip.block_height, @@ -1898,7 +1898,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, first_lockup_amt,); } @@ -1918,7 +1918,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, first_lockup_amt,); } @@ -1963,7 +1963,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, first_lockup_amt,); } @@ -1978,7 +1978,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!( reward_set_entries[0].amount_stacked, @@ -2111,7 +2111,7 @@ fn test_lock_period_invariant_extend_transition() { 0, ALICE_LOCKUP, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 4, tip.block_height, ); @@ -2177,7 +2177,7 @@ fn test_lock_period_invariant_extend_transition() { 1, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, ); @@ -2290,7 +2290,7 @@ fn test_pox_extend_transition_pox_2() { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[0].1, ALICE_LOCKUP); }; @@ -2326,7 +2326,7 @@ fn test_pox_extend_transition_pox_2() { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&bob).bytes + key_to_stacks_addr(&bob).destruct().1, ); assert_eq!(reward_addrs[0].1, BOB_LOCKUP); @@ -2336,7 +2336,7 @@ fn test_pox_extend_transition_pox_2() { ); assert_eq!( (reward_addrs[1].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[1].1, ALICE_LOCKUP); }; @@ -2363,7 +2363,7 @@ fn test_pox_extend_transition_pox_2() { 0, ALICE_LOCKUP, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 4, tip.block_height, ); @@ -2431,7 +2431,7 @@ fn test_pox_extend_transition_pox_2() { BOB_LOCKUP, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 3, tip.block_height, @@ -2443,7 +2443,7 @@ fn test_pox_extend_transition_pox_2() { 1, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, ); @@ -2461,7 +2461,7 @@ fn test_pox_extend_transition_pox_2() { 1, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 1, ); @@ -2509,7 +2509,7 @@ fn test_pox_extend_transition_pox_2() { 2, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 12, tip.block_height, ); @@ -2727,7 +2727,7 @@ fn test_delegate_extend_transition_pox_2() { (reward_addrs[0].0).version(), AddressHashMode::SerializeP2PKH as u8 ); - assert_eq!(&(reward_addrs[0].0).hash160(), &charlie_address.bytes); + assert_eq!(&(reward_addrs[0].0).hash160(), charlie_address.bytes()); // 1 lockup was done between alice's first cycle and the start of v2 cycles assert_eq!(reward_addrs[0].1, 1 * LOCKUP_AMT); }; @@ -2761,7 +2761,7 @@ fn test_delegate_extend_transition_pox_2() { (reward_addrs[0].0).version(), AddressHashMode::SerializeP2PKH as u8 ); - assert_eq!(&(reward_addrs[0].0).hash160(), &charlie_address.bytes); + assert_eq!(&(reward_addrs[0].0).hash160(), charlie_address.bytes()); // 2 lockups were performed in v2 cycles assert_eq!(reward_addrs[0].1, 2 * LOCKUP_AMT); }; @@ -2804,7 +2804,7 @@ fn test_delegate_extend_transition_pox_2() { Value::UInt(LOCKUP_AMT), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(tip.block_height as u128), Value::UInt(4), @@ -2819,7 +2819,7 @@ fn test_delegate_extend_transition_pox_2() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(EXPECTED_ALICE_FIRST_REWARD_CYCLE), ], @@ -2832,7 +2832,7 @@ fn test_delegate_extend_transition_pox_2() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(EXPECTED_ALICE_FIRST_REWARD_CYCLE + 1), ], @@ -2845,7 +2845,7 @@ fn test_delegate_extend_transition_pox_2() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(EXPECTED_ALICE_FIRST_REWARD_CYCLE + 2), ], @@ -2858,7 +2858,7 @@ fn test_delegate_extend_transition_pox_2() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(EXPECTED_ALICE_FIRST_REWARD_CYCLE + 3), ], @@ -2964,7 +2964,7 @@ fn test_delegate_extend_transition_pox_2() { Value::UInt(LOCKUP_AMT), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(tip.block_height as u128), Value::UInt(3), @@ -2980,7 +2980,7 @@ fn test_delegate_extend_transition_pox_2() { PrincipalData::from(alice_address.clone()).into(), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(6), ], @@ -2996,7 +2996,7 @@ fn test_delegate_extend_transition_pox_2() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(first_v2_cycle as u128), ], @@ -3009,7 +3009,7 @@ fn test_delegate_extend_transition_pox_2() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(first_v2_cycle as u128 + 1), ], @@ -3022,7 +3022,7 @@ fn test_delegate_extend_transition_pox_2() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(first_v2_cycle as u128 + 2), ], @@ -3089,7 +3089,7 @@ fn test_delegate_extend_transition_pox_2() { PrincipalData::from(bob_address.clone()).into(), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(1), ], @@ -3102,7 +3102,7 @@ fn test_delegate_extend_transition_pox_2() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(first_v2_cycle as u128 + 3), ], @@ -3171,7 +3171,7 @@ fn test_delegate_extend_transition_pox_2() { PrincipalData::from(bob_address.clone()).into(), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(1), ], @@ -3236,7 +3236,7 @@ fn test_delegate_extend_transition_pox_2() { 2, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 12, tip.block_height, ); @@ -3461,7 +3461,7 @@ fn test_pox_2_getters() { LOCKUP_AMT, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 4, tip.block_height, @@ -3490,7 +3490,7 @@ fn test_pox_2_getters() { Value::UInt(LOCKUP_AMT), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(tip.block_height as u128), Value::UInt(4), @@ -3504,7 +3504,7 @@ fn test_pox_2_getters() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(cur_reward_cycle as u128), ], @@ -3517,7 +3517,7 @@ fn test_pox_2_getters() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(cur_reward_cycle as u128 + 1), ], @@ -3530,7 +3530,7 @@ fn test_pox_2_getters() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(cur_reward_cycle as u128 + 2), ], @@ -3578,10 +3578,10 @@ fn test_pox_2_getters() { }}", &alice_address, &bob_address, &bob_address, &format!("{}.hello-world", &charlie_address), cur_reward_cycle + 1, - &charlie_address.bytes, cur_reward_cycle + 0, &charlie_address, - &charlie_address.bytes, cur_reward_cycle + 1, &charlie_address, - &charlie_address.bytes, cur_reward_cycle + 2, &charlie_address, - &charlie_address.bytes, cur_reward_cycle + 3, &charlie_address, + charlie_address.bytes(), cur_reward_cycle + 0, &charlie_address, + charlie_address.bytes(), cur_reward_cycle + 1, &charlie_address, + charlie_address.bytes(), cur_reward_cycle + 2, &charlie_address, + charlie_address.bytes(), cur_reward_cycle + 3, &charlie_address, cur_reward_cycle, cur_reward_cycle + 1, cur_reward_cycle + 2, @@ -3769,7 +3769,10 @@ fn test_get_pox_addrs() { key, 0, 1024 * POX_THRESHOLD_STEPS_USTX, - PoxAddress::from_legacy(*hash_mode, key_to_stacks_addr(key).bytes), + PoxAddress::from_legacy( + *hash_mode, + key_to_stacks_addr(key).destruct().1, + ), 2, tip.block_height, ); @@ -4270,10 +4273,7 @@ fn test_stack_with_segwit() { PoxAddress::Addr32(false, PoxAddressType32::P2WSH, [0x02; 32]), PoxAddress::Addr32(false, PoxAddressType32::P2TR, [0x03; 32]), PoxAddress::Standard( - StacksAddress { - version: 26, - bytes: Hash160([0x04; 20]), - }, + StacksAddress::new(26, Hash160([0x04; 20])).unwrap(), Some(AddressHashMode::SerializeP2PKH), ), ]; @@ -4357,7 +4357,7 @@ fn test_pox_2_delegate_stx_addr_validation() { Value::none(), Value::some(make_pox_addr( AddressHashMode::SerializeP2PKH, - alice_address.bytes.clone(), + alice_address.bytes().clone(), )) .unwrap(), ], @@ -4372,7 +4372,7 @@ fn test_pox_2_delegate_stx_addr_validation() { ( ClarityName::try_from("hashbytes".to_owned()).unwrap(), Value::Sequence(SequenceData::Buffer(BuffData { - data: bob_address.bytes.as_bytes().to_vec(), + data: bob_address.bytes().as_bytes().to_vec(), })), ), ]) @@ -4461,7 +4461,10 @@ fn test_pox_2_delegate_stx_addr_validation() { assert_eq!( alice_pox_addr, - make_pox_addr(AddressHashMode::SerializeP2PKH, alice_address.bytes.clone(),) + make_pox_addr( + AddressHashMode::SerializeP2PKH, + alice_address.bytes().clone(), + ) ); } @@ -4521,17 +4524,17 @@ fn stack_aggregation_increase() { let bob = keys.pop().unwrap(); let bob_address = key_to_stacks_addr(&bob); let bob_principal = PrincipalData::from(bob_address.clone()); - let bob_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, bob_address.bytes.clone()); + let bob_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, bob_address.bytes().clone()); let charlie = keys.pop().unwrap(); let charlie_address = key_to_stacks_addr(&charlie); let charlie_pox_addr = make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ); let dan = keys.pop().unwrap(); let dan_address = key_to_stacks_addr(&dan); let dan_principal = PrincipalData::from(dan_address.clone()); - let dan_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, dan_address.bytes.clone()); + let dan_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, dan_address.bytes().clone()); let alice_nonce = 0; let mut bob_nonce = 0; let mut charlie_nonce = 0; @@ -4585,7 +4588,7 @@ fn stack_aggregation_increase() { &dan, dan_nonce, dan_stack_amount, - PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, dan_address.bytes.clone()), + PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, dan_address.bytes().clone()), 12, tip.block_height, ); @@ -4967,12 +4970,14 @@ fn stack_in_both_pox1_and_pox2() { let alice = keys.pop().unwrap(); let alice_address = key_to_stacks_addr(&alice); - let alice_pox_addr = - make_pox_addr(AddressHashMode::SerializeP2PKH, alice_address.bytes.clone()); + let alice_pox_addr = make_pox_addr( + AddressHashMode::SerializeP2PKH, + alice_address.bytes().clone(), + ); let bob = keys.pop().unwrap(); let bob_address = key_to_stacks_addr(&bob); - let bob_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, bob_address.bytes.clone()); + let bob_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, bob_address.bytes().clone()); let mut alice_nonce = 0; let mut bob_nonce = 0; @@ -4999,7 +5004,7 @@ fn stack_in_both_pox1_and_pox2() { alice_nonce, alice_first_lock_amount, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 12, tip.block_height, ); @@ -5033,7 +5038,7 @@ fn stack_in_both_pox1_and_pox2() { bob_nonce, bob_first_lock_amount, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, 12, tip.block_height, ); diff --git a/stackslib/src/chainstate/stacks/boot/pox_3_tests.rs b/stackslib/src/chainstate/stacks/boot/pox_3_tests.rs index 5c52297969..0447959a76 100644 --- a/stackslib/src/chainstate/stacks/boot/pox_3_tests.rs +++ b/stackslib/src/chainstate/stacks/boot/pox_3_tests.rs @@ -238,7 +238,7 @@ fn simple_pox_lockup_transition_pox_2() { 0, 1024 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 4, tip.block_height, ); @@ -322,7 +322,7 @@ fn simple_pox_lockup_transition_pox_2() { 512 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 6, tip.block_height, @@ -348,7 +348,7 @@ fn simple_pox_lockup_transition_pox_2() { 1, 512 * POX_THRESHOLD_STEPS_USTX, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, 4, tip.block_height, ); @@ -365,7 +365,7 @@ fn simple_pox_lockup_transition_pox_2() { 512 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 12, tip.block_height, @@ -409,7 +409,7 @@ fn simple_pox_lockup_transition_pox_2() { 512 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 6, tip, @@ -421,7 +421,7 @@ fn simple_pox_lockup_transition_pox_2() { 512 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, tip, @@ -630,7 +630,7 @@ fn pox_auto_unlock(alice_first: bool) { 1024 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, tip.block_height, @@ -642,7 +642,7 @@ fn pox_auto_unlock(alice_first: bool) { 1 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 6, tip.block_height, @@ -663,11 +663,11 @@ fn pox_auto_unlock(alice_first: bool) { assert_eq!(reward_set_entries.len(), 2); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&bob).bytes.0.to_vec() + key_to_stacks_addr(&bob).bytes().0.to_vec() ); assert_eq!( reward_set_entries[1].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); } @@ -697,7 +697,7 @@ fn pox_auto_unlock(alice_first: bool) { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); } @@ -791,7 +791,7 @@ fn pox_auto_unlock(alice_first: bool) { 1024 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, tip.block_height, @@ -803,7 +803,7 @@ fn pox_auto_unlock(alice_first: bool) { 1 * POX_THRESHOLD_STEPS_USTX, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 6, tip.block_height, @@ -824,11 +824,11 @@ fn pox_auto_unlock(alice_first: bool) { assert_eq!(reward_set_entries.len(), 2); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&bob).bytes.0.to_vec() + key_to_stacks_addr(&bob).bytes().0.to_vec() ); assert_eq!( reward_set_entries[1].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); } @@ -857,7 +857,7 @@ fn pox_auto_unlock(alice_first: bool) { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); } @@ -1045,7 +1045,7 @@ fn delegate_stack_increase() { let bob = keys.pop().unwrap(); let bob_address = key_to_stacks_addr(&bob); let bob_principal = PrincipalData::from(bob_address.clone()); - let bob_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, bob_address.bytes.clone()); + let bob_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, bob_address.bytes().clone()); let mut alice_nonce = 0; let mut bob_nonce = 0; @@ -1691,7 +1691,7 @@ fn stack_increase() { first_lockup_amt, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, tip.block_height, @@ -1715,7 +1715,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, first_lockup_amt,); } @@ -1735,7 +1735,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, first_lockup_amt,); } @@ -1773,7 +1773,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, first_lockup_amt,); } @@ -1793,7 +1793,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!( reward_set_entries[0].amount_stacked, @@ -1859,7 +1859,7 @@ fn stack_increase() { first_lockup_amt, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, tip.block_height, @@ -1882,7 +1882,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, first_lockup_amt,); } @@ -1902,7 +1902,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, first_lockup_amt,); } @@ -1950,7 +1950,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, first_lockup_amt,); } @@ -1965,7 +1965,7 @@ fn stack_increase() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!( reward_set_entries[0].amount_stacked, @@ -2138,7 +2138,7 @@ fn pox_extend_transition() { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[0].1, ALICE_LOCKUP); }; @@ -2174,7 +2174,7 @@ fn pox_extend_transition() { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&bob).bytes + key_to_stacks_addr(&bob).destruct().1, ); assert_eq!(reward_addrs[0].1, BOB_LOCKUP); @@ -2184,7 +2184,7 @@ fn pox_extend_transition() { ); assert_eq!( (reward_addrs[1].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[1].1, ALICE_LOCKUP); }; @@ -2204,7 +2204,7 @@ fn pox_extend_transition() { 0, ALICE_LOCKUP, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 4, tip.block_height, ); @@ -2267,7 +2267,7 @@ fn pox_extend_transition() { BOB_LOCKUP, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 3, tip.block_height, @@ -2279,7 +2279,7 @@ fn pox_extend_transition() { 1, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, ); @@ -2293,7 +2293,7 @@ fn pox_extend_transition() { 1, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 1, ); @@ -2358,7 +2358,7 @@ fn pox_extend_transition() { ALICE_LOCKUP, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 4, tip.block_height, @@ -2377,7 +2377,7 @@ fn pox_extend_transition() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, ALICE_LOCKUP,); } @@ -2406,7 +2406,7 @@ fn pox_extend_transition() { BOB_LOCKUP, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 3, tip.block_height, @@ -2418,7 +2418,7 @@ fn pox_extend_transition() { 3, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, ); @@ -2436,7 +2436,7 @@ fn pox_extend_transition() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, ALICE_LOCKUP,); } @@ -2447,12 +2447,12 @@ fn pox_extend_transition() { assert_eq!(reward_set_entries.len(), 2); assert_eq!( reward_set_entries[1].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[1].amount_stacked, ALICE_LOCKUP,); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&bob).bytes.0.to_vec() + key_to_stacks_addr(&bob).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, BOB_LOCKUP,); } @@ -2463,7 +2463,7 @@ fn pox_extend_transition() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, ALICE_LOCKUP,); } @@ -2668,7 +2668,7 @@ fn delegate_extend_pox_3() { Value::UInt(LOCKUP_AMT), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(tip.block_height as u128), Value::UInt(3), @@ -2689,7 +2689,7 @@ fn delegate_extend_pox_3() { Value::UInt(LOCKUP_AMT), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(tip.block_height as u128), Value::UInt(6), @@ -2708,7 +2708,7 @@ fn delegate_extend_pox_3() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(first_v3_cycle as u128 + ix), ], @@ -2733,7 +2733,7 @@ fn delegate_extend_pox_3() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&charlie).bytes.0.to_vec() + key_to_stacks_addr(&charlie).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, 2 * LOCKUP_AMT); } @@ -2791,7 +2791,7 @@ fn delegate_extend_pox_3() { PrincipalData::from(bob_address.clone()).into(), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(1), ], @@ -2808,7 +2808,7 @@ fn delegate_extend_pox_3() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(first_v3_cycle as u128 + 3), ], @@ -2860,7 +2860,7 @@ fn delegate_extend_pox_3() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&charlie).bytes.0.to_vec() + key_to_stacks_addr(&charlie).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, 2 * LOCKUP_AMT); } @@ -2884,7 +2884,7 @@ fn delegate_extend_pox_3() { PrincipalData::from(bob_address.clone()).into(), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(3), ], @@ -3112,7 +3112,7 @@ fn pox_3_getters() { LOCKUP_AMT, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 4, tip.block_height, @@ -3141,7 +3141,7 @@ fn pox_3_getters() { Value::UInt(LOCKUP_AMT), make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(tip.block_height as u128), Value::UInt(4), @@ -3155,7 +3155,7 @@ fn pox_3_getters() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(first_v3_cycle as u128), ], @@ -3168,7 +3168,7 @@ fn pox_3_getters() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(first_v3_cycle as u128 + 1), ], @@ -3181,7 +3181,7 @@ fn pox_3_getters() { vec![ make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ), Value::UInt(first_v3_cycle as u128 + 2), ], @@ -3229,10 +3229,10 @@ fn pox_3_getters() { }}", &alice_address, &bob_address, &bob_address, &format!("{}.hello-world", &charlie_address), first_v3_cycle + 1, - &charlie_address.bytes, first_v3_cycle + 0, &charlie_address, - &charlie_address.bytes, first_v3_cycle + 1, &charlie_address, - &charlie_address.bytes, first_v3_cycle + 2, &charlie_address, - &charlie_address.bytes, first_v3_cycle + 3, &charlie_address, + charlie_address.bytes(), first_v3_cycle + 0, &charlie_address, + charlie_address.bytes(), first_v3_cycle + 1, &charlie_address, + charlie_address.bytes(), first_v3_cycle + 2, &charlie_address, + charlie_address.bytes(), first_v3_cycle + 3, &charlie_address, first_v3_cycle, first_v3_cycle + 1, first_v3_cycle + 2, @@ -3523,7 +3523,7 @@ fn get_pox_addrs() { AddressHashMode::SerializeP2WSH, ]) .map(|(key, hash_mode)| { - let pox_addr = PoxAddress::from_legacy(hash_mode, key_to_stacks_addr(key).bytes); + let pox_addr = PoxAddress::from_legacy(hash_mode, key_to_stacks_addr(key).destruct().1); txs.push(make_pox_3_lockup( key, 0, @@ -3870,17 +3870,17 @@ fn stack_aggregation_increase() { let bob = keys.pop().unwrap(); let bob_address = key_to_stacks_addr(&bob); let bob_principal = PrincipalData::from(bob_address.clone()); - let bob_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, bob_address.bytes.clone()); + let bob_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, bob_address.bytes().clone()); let charlie = keys.pop().unwrap(); let charlie_address = key_to_stacks_addr(&charlie); let charlie_pox_addr = make_pox_addr( AddressHashMode::SerializeP2PKH, - charlie_address.bytes.clone(), + charlie_address.bytes().clone(), ); let dan = keys.pop().unwrap(); let dan_address = key_to_stacks_addr(&dan); let dan_principal = PrincipalData::from(dan_address.clone()); - let dan_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, dan_address.bytes.clone()); + let dan_pox_addr = make_pox_addr(AddressHashMode::SerializeP2PKH, dan_address.bytes().clone()); let alice_nonce = 0; let mut bob_nonce = 0; let mut charlie_nonce = 0; @@ -3937,7 +3937,7 @@ fn stack_aggregation_increase() { &dan, dan_nonce, dan_stack_amount, - PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, dan_address.bytes.clone()), + PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, dan_address.bytes().clone()), 12, tip.block_height, ); @@ -4333,7 +4333,7 @@ fn pox_3_delegate_stx_addr_validation() { Value::none(), Value::some(make_pox_addr( AddressHashMode::SerializeP2PKH, - alice_address.bytes.clone(), + alice_address.bytes().clone(), )) .unwrap(), ], @@ -4348,7 +4348,7 @@ fn pox_3_delegate_stx_addr_validation() { ( ClarityName::try_from("hashbytes".to_owned()).unwrap(), Value::Sequence(SequenceData::Buffer(BuffData { - data: bob_address.bytes.as_bytes().to_vec(), + data: bob_address.bytes().as_bytes().to_vec(), })), ), ]) @@ -4437,6 +4437,9 @@ fn pox_3_delegate_stx_addr_validation() { assert_eq!( alice_pox_addr, - make_pox_addr(AddressHashMode::SerializeP2PKH, alice_address.bytes.clone(),) + make_pox_addr( + AddressHashMode::SerializeP2PKH, + alice_address.bytes().clone(), + ) ); } diff --git a/stackslib/src/chainstate/stacks/boot/pox_4_tests.rs b/stackslib/src/chainstate/stacks/boot/pox_4_tests.rs index 840e7a2c54..74a3c29cad 100644 --- a/stackslib/src/chainstate/stacks/boot/pox_4_tests.rs +++ b/stackslib/src/chainstate/stacks/boot/pox_4_tests.rs @@ -111,7 +111,7 @@ fn make_simple_pox_4_lock( lock_period: u128, ) -> StacksTransaction { let addr = key_to_stacks_addr(key); - let pox_addr = PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, addr.bytes.clone()); + let pox_addr = PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, addr.bytes().clone()); let signer_pk = StacksPublicKey::from_private(&key); let tip = get_tip(peer.sortdb.as_ref()); let next_reward_cycle = peer @@ -343,7 +343,7 @@ fn pox_extend_transition() { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1 ); assert_eq!(reward_addrs[0].1, ALICE_LOCKUP); }; @@ -379,7 +379,7 @@ fn pox_extend_transition() { ); assert_eq!( (reward_addrs[0].0).hash160(), - key_to_stacks_addr(&bob).bytes + key_to_stacks_addr(&bob).destruct().1, ); assert_eq!(reward_addrs[0].1, BOB_LOCKUP); @@ -389,7 +389,7 @@ fn pox_extend_transition() { ); assert_eq!( (reward_addrs[1].0).hash160(), - key_to_stacks_addr(&alice).bytes + key_to_stacks_addr(&alice).destruct().1, ); assert_eq!(reward_addrs[1].1, ALICE_LOCKUP); }; @@ -409,7 +409,7 @@ fn pox_extend_transition() { 0, ALICE_LOCKUP, AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, 4, tip.block_height, ); @@ -472,7 +472,7 @@ fn pox_extend_transition() { BOB_LOCKUP, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 3, tip.block_height, @@ -484,7 +484,7 @@ fn pox_extend_transition() { 1, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 6, ); @@ -498,7 +498,7 @@ fn pox_extend_transition() { 1, PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ), 1, ); @@ -564,7 +564,7 @@ fn pox_extend_transition() { let alice_pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ); let auth_id = 1; @@ -585,7 +585,7 @@ fn pox_extend_transition() { ALICE_LOCKUP, &PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&alice).bytes, + key_to_stacks_addr(&alice).destruct().1, ), 4, &alice_signer_key, @@ -614,7 +614,7 @@ fn pox_extend_transition() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, ALICE_LOCKUP,); } @@ -642,7 +642,7 @@ fn pox_extend_transition() { let bob_pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(&bob).bytes, + key_to_stacks_addr(&bob).destruct().1, ); let bob_signature = make_signer_key_signature( @@ -708,7 +708,7 @@ fn pox_extend_transition() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, ALICE_LOCKUP); } @@ -719,12 +719,12 @@ fn pox_extend_transition() { assert_eq!(reward_set_entries.len(), 2); assert_eq!( reward_set_entries[1].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[1].amount_stacked, ALICE_LOCKUP); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&bob).bytes.0.to_vec() + key_to_stacks_addr(&bob).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, BOB_LOCKUP); } @@ -736,7 +736,7 @@ fn pox_extend_transition() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - key_to_stacks_addr(&alice).bytes.0.to_vec() + key_to_stacks_addr(&alice).bytes().0.to_vec() ); assert_eq!(reward_set_entries[0].amount_stacked, ALICE_LOCKUP); } @@ -960,7 +960,7 @@ fn pox_lock_unlock() { ]) .enumerate() .map(|(ix, (key, hash_mode))| { - let pox_addr = PoxAddress::from_legacy(hash_mode, key_to_stacks_addr(key).bytes); + let pox_addr = PoxAddress::from_legacy(hash_mode, key_to_stacks_addr(key).destruct().1); let lock_period = if ix == 3 { 12 } else { lock_period }; let signer_key = key; let signature = make_signer_key_signature( @@ -1139,7 +1139,7 @@ fn pox_3_defunct() { AddressHashMode::SerializeP2WSH, ]) .map(|(key, hash_mode)| { - let pox_addr = PoxAddress::from_legacy(hash_mode, key_to_stacks_addr(key).bytes); + let pox_addr = PoxAddress::from_legacy(hash_mode, key_to_stacks_addr(key).destruct().1); txs.push(make_pox_3_lockup( key, 0, @@ -1269,7 +1269,7 @@ fn pox_3_unlocks() { AddressHashMode::SerializeP2WSH, ]) .map(|(key, hash_mode)| { - let pox_addr = PoxAddress::from_legacy(hash_mode, key_to_stacks_addr(key).bytes); + let pox_addr = PoxAddress::from_legacy(hash_mode, key_to_stacks_addr(key).destruct().1); txs.push(make_pox_3_lockup( key, 0, @@ -1417,8 +1417,10 @@ fn pox_4_check_cycle_id_range_in_print_events_pool() { let steph_key = keys.pop().unwrap(); let steph_address = key_to_stacks_addr(&steph_key); let steph_principal = PrincipalData::from(steph_address.clone()); - let steph_pox_addr_val = - make_pox_addr(AddressHashMode::SerializeP2PKH, steph_address.bytes.clone()); + let steph_pox_addr_val = make_pox_addr( + AddressHashMode::SerializeP2PKH, + steph_address.bytes().clone(), + ); let steph_pox_addr = pox_addr_from(&steph_key); let steph_signing_key = Secp256k1PublicKey::from_private(&steph_key); let steph_key_val = Value::buff_from(steph_signing_key.to_bytes_compressed()).unwrap(); @@ -1806,8 +1808,10 @@ fn pox_4_check_cycle_id_range_in_print_events_pool_in_prepare_phase() { let steph_key = keys.pop().unwrap(); let steph_address = key_to_stacks_addr(&steph_key); let steph_principal = PrincipalData::from(steph_address.clone()); - let steph_pox_addr_val = - make_pox_addr(AddressHashMode::SerializeP2PKH, steph_address.bytes.clone()); + let steph_pox_addr_val = make_pox_addr( + AddressHashMode::SerializeP2PKH, + steph_address.bytes().clone(), + ); let steph_pox_addr = pox_addr_from(&steph_key); let steph_signing_key = Secp256k1PublicKey::from_private(&steph_key); let steph_key_val = Value::buff_from(steph_signing_key.to_bytes_compressed()).unwrap(); @@ -2450,8 +2454,10 @@ fn pox_4_check_cycle_id_range_in_print_events_before_prepare_phase() { let steph_key = keys.pop().unwrap(); let steph_address = key_to_stacks_addr(&steph_key); let steph_principal = PrincipalData::from(steph_address.clone()); - let steph_pox_addr_val = - make_pox_addr(AddressHashMode::SerializeP2PKH, steph_address.bytes.clone()); + let steph_pox_addr_val = make_pox_addr( + AddressHashMode::SerializeP2PKH, + steph_address.bytes().clone(), + ); let steph_pox_addr = pox_addr_from(&steph_key); let steph_signing_key = Secp256k1PublicKey::from_private(&steph_key); let steph_key_val = Value::buff_from(steph_signing_key.to_bytes_compressed()).unwrap(); @@ -2571,8 +2577,10 @@ fn pox_4_check_cycle_id_range_in_print_events_in_prepare_phase() { let steph_key = keys.pop().unwrap(); let steph_address = key_to_stacks_addr(&steph_key); let steph_principal = PrincipalData::from(steph_address.clone()); - let steph_pox_addr_val = - make_pox_addr(AddressHashMode::SerializeP2PKH, steph_address.bytes.clone()); + let steph_pox_addr_val = make_pox_addr( + AddressHashMode::SerializeP2PKH, + steph_address.bytes().clone(), + ); let steph_pox_addr = pox_addr_from(&steph_key); let steph_signing_key = Secp256k1PublicKey::from_private(&steph_key); let steph_key_val = Value::buff_from(steph_signing_key.to_bytes_compressed()).unwrap(); @@ -2807,8 +2815,10 @@ fn pox_4_revoke_delegate_stx_events() { let steph = keys.pop().unwrap(); let steph_address = key_to_stacks_addr(&steph); let steph_principal = PrincipalData::from(steph_address.clone()); - let steph_pox_addr = - make_pox_addr(AddressHashMode::SerializeP2PKH, steph_address.bytes.clone()); + let steph_pox_addr = make_pox_addr( + AddressHashMode::SerializeP2PKH, + steph_address.bytes().clone(), + ); let steph_signing_key = Secp256k1PublicKey::from_private(&steph); let steph_key_val = Value::buff_from(steph_signing_key.to_bytes_compressed()).unwrap(); @@ -3053,9 +3063,12 @@ fn verify_signer_key_signatures() { let expected_error = Value::error(Value::Int(35)).unwrap(); - let alice_pox_addr = - PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, alice_address.bytes.clone()); - let bob_pox_addr = PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, bob_address.bytes); + let alice_pox_addr = PoxAddress::from_legacy( + AddressHashMode::SerializeP2PKH, + alice_address.bytes().clone(), + ); + let bob_pox_addr = + PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, bob_address.bytes().clone()); let period = 1_u128; @@ -3323,7 +3336,7 @@ fn stack_stx_verify_signer_sig(use_nakamoto: bool) { let second_stacker_addr = key_to_stacks_addr(second_stacker); let second_stacker_pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - second_stacker_addr.bytes.clone(), + second_stacker_addr.bytes().clone(), ); let reward_cycle = get_current_reward_cycle(&peer, &burnchain); @@ -4224,7 +4237,7 @@ impl StackerSignerInfo { let public_key = StacksPublicKey::from_private(&private_key); let address = key_to_stacks_addr(&private_key); let pox_address = - PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, address.bytes.clone()); + PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, address.bytes().clone()); let principal = PrincipalData::from(address.clone()); let nonce = 0; Self { @@ -6151,7 +6164,7 @@ fn delegate_stack_stx_extend_signer_key(use_nakamoto: bool) { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(bob_delegate_private_key).bytes, + key_to_stacks_addr(bob_delegate_private_key).destruct().1, ); let delegate_stx = make_pox_4_delegate_stx( @@ -6356,7 +6369,7 @@ fn stack_increase(use_nakamoto: bool) { let min_ustx = get_stacking_minimum(&mut peer, &latest_block); let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(alice_stacking_private_key).bytes, + key_to_stacks_addr(alice_stacking_private_key).destruct().1, ); let reward_cycle = get_current_reward_cycle(&peer, &burnchain); @@ -6535,7 +6548,7 @@ fn delegate_stack_increase(use_nakamoto: bool) { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(bob_delegate_key).bytes, + key_to_stacks_addr(bob_delegate_key).destruct().1, ); let next_reward_cycle = 1 + burnchain @@ -7276,6 +7289,344 @@ fn test_scenario_one(use_nakamoto: bool) { assert_eq!(bob_tx_result, Value::Int(19)); } +#[test] +// In this test two solo stacker-signers Alice & Bob sign & stack +// for two reward cycles. Alice provides a signature, Bob uses +// 'set-signer-key-authorizations' to authorize. Two cycles later, +// when no longer stacked, they both try replaying their auths. +fn test_deser_abort() { + // Alice solo stacker-signer setup + let mut alice = StackerSignerInfo::new(); + // Bob solo stacker-signer setup + let mut bob = StackerSignerInfo::new(); + let default_initial_balances: u64 = 1_000_000_000_000_000_000; + let initial_balances = vec![ + (alice.principal.clone(), default_initial_balances), + (bob.principal.clone(), default_initial_balances), + ]; + + let observer = TestEventObserver::new(); + let ( + mut peer, + mut peer_nonce, + burn_block_height, + reward_cycle, + next_reward_cycle, + min_ustx, + peer_config, + mut test_signers, + ) = pox_4_scenario_test_setup("test_scenario_one", &observer, initial_balances, true); + + // Add alice and bob to test_signers + if let Some(ref mut test_signers) = test_signers.as_mut() { + test_signers + .signer_keys + .extend(vec![alice.private_key.clone(), bob.private_key.clone()]); + } + + // Alice Signatures + let amount = (default_initial_balances / 2).wrapping_sub(1000) as u128; + let lock_period = 1; + let alice_signature = make_signer_key_signature( + &alice.pox_address, + &alice.private_key, + reward_cycle, + &Pox4SignatureTopic::StackStx, + lock_period, + u128::MAX, + 1, + ); + let alice_signature_err = make_signer_key_signature( + &alice.pox_address, + &alice.private_key, + reward_cycle - 1, + &Pox4SignatureTopic::StackStx, + lock_period, + 100, + 2, + ); + + // Bob Authorizations + let bob_authorization_low = make_pox_4_set_signer_key_auth( + &bob.pox_address, + &bob.private_key, + reward_cycle, + &Pox4SignatureTopic::StackStx, + lock_period, + true, + bob.nonce, + Some(&bob.private_key), + 100, + 2, + ); + bob.nonce += 1; + let bob_authorization = make_pox_4_set_signer_key_auth( + &bob.pox_address, + &bob.private_key, + reward_cycle, + &Pox4SignatureTopic::StackStx, + lock_period, + true, + bob.nonce, + Some(&bob.private_key), + u128::MAX, + 3, + ); + bob.nonce += 1; + + // Alice stacks + let alice_err_nonce = alice.nonce; + let alice_stack_err = make_pox_4_lockup( + &alice.private_key, + alice_err_nonce, + amount, + &alice.pox_address, + lock_period, + &alice.public_key, + burn_block_height, + Some(alice_signature_err), + 100, + 1, + ); + + let alice_stack_nonce = alice_err_nonce + 1; + let alice_stack = make_pox_4_lockup( + &alice.private_key, + alice_stack_nonce, + amount, + &alice.pox_address, + lock_period, + &alice.public_key, + burn_block_height, + Some(alice_signature.clone()), + u128::MAX, + 1, + ); + alice.nonce = alice_stack_nonce + 1; + + // Bob stacks + let bob_nonce_stack_err = bob.nonce; + let bob_stack_err = make_pox_4_lockup( + &bob.private_key, + bob_nonce_stack_err, + amount, + &bob.pox_address, + lock_period, + &bob.public_key, + burn_block_height, + None, + 100, + 2, + ); + let bob_nonce_stack = bob_nonce_stack_err + 1; + let bob_stack = make_pox_4_lockup( + &bob.private_key, + bob_nonce_stack, + amount, + &bob.pox_address, + lock_period, + &bob.public_key, + burn_block_height, + None, + u128::MAX, + 3, + ); + bob.nonce = bob_nonce_stack + 1; + + let txs = vec![ + bob_authorization_low, + bob_authorization, + alice_stack_err, + alice_stack, + bob_stack_err, + bob_stack, + ]; + + // Commit tx & advance to the reward set calculation height (2nd block of the prepare phase) + let target_height = peer + .config + .burnchain + .reward_cycle_to_block_height(next_reward_cycle as u64) + .saturating_sub(peer.config.burnchain.pox_constants.prepare_length as u64) + .wrapping_add(2); + let (latest_block, tx_block, receipts) = advance_to_block_height( + &mut peer, + &observer, + &txs, + &mut peer_nonce, + target_height, + &mut test_signers, + ); + + // Verify Alice stacked + let (pox_address, first_reward_cycle, lock_period, _indices) = + get_stacker_info_pox_4(&mut peer, &alice.principal) + .expect("Failed to find alice initial stack-stx"); + assert_eq!(first_reward_cycle, next_reward_cycle); + assert_eq!(pox_address, alice.pox_address); + + // Verify Bob stacked + let (pox_address, first_reward_cycle, lock_period, _indices) = + get_stacker_info_pox_4(&mut peer, &bob.principal) + .expect("Failed to find bob initial stack-stx"); + assert_eq!(first_reward_cycle, next_reward_cycle); + assert_eq!(pox_address, bob.pox_address); + + // 1. Check bob's low authorization transaction + let bob_tx_result_low = receipts + .get(1) + .unwrap() + .result + .clone() + .expect_result_ok() + .unwrap(); + assert_eq!(bob_tx_result_low, Value::Bool(true)); + + // 2. Check bob's expected authorization transaction + let bob_tx_result_ok = receipts + .get(2) + .unwrap() + .result + .clone() + .expect_result_ok() + .unwrap(); + assert_eq!(bob_tx_result_ok, Value::Bool(true)); + + // 3. Check alice's low stack transaction + let alice_tx_result_err = receipts + .get(3) + .unwrap() + .result + .clone() + .expect_result_err() + .unwrap(); + assert_eq!(alice_tx_result_err, Value::Int(38)); + + // Get alice's expected stack transaction + let alice_tx_result_ok = receipts + .get(4) + .unwrap() + .result + .clone() + .expect_result_ok() + .unwrap() + .expect_tuple() + .unwrap(); + + // 4.1 Check amount locked + let amount_locked_expected = Value::UInt(amount); + let amount_locked_actual = alice_tx_result_ok + .data_map + .get("lock-amount") + .unwrap() + .clone(); + assert_eq!(amount_locked_actual, amount_locked_expected); + + // 4.2 Check signer key + let signer_key_expected = Value::buff_from(alice.public_key.to_bytes_compressed()).unwrap(); + let signer_key_actual = alice_tx_result_ok + .data_map + .get("signer-key") + .unwrap() + .clone(); + assert_eq!(signer_key_expected, signer_key_actual); + + // 4.3 Check unlock height + let unlock_height_expected = Value::UInt( + peer.config + .burnchain + .reward_cycle_to_block_height(next_reward_cycle as u64 + lock_period as u64) + .wrapping_sub(1) as u128, + ); + let unlock_height_actual = alice_tx_result_ok + .data_map + .get("unlock-burn-height") + .unwrap() + .clone(); + assert_eq!(unlock_height_expected, unlock_height_actual); + + // 5. Check bob's error stack transaction + let bob_tx_result_err = receipts + .get(5) + .unwrap() + .result + .clone() + .expect_result_err() + .unwrap(); + assert_eq!(bob_tx_result_err, Value::Int(38)); + + // Get bob's expected stack transaction + let bob_tx_result_ok = receipts + .get(6) + .unwrap() + .result + .clone() + .expect_result_ok() + .unwrap() + .expect_tuple() + .unwrap(); + + // 6.1 Check amount locked + let amount_locked_expected = Value::UInt(amount); + let amount_locked_actual = bob_tx_result_ok + .data_map + .get("lock-amount") + .unwrap() + .clone(); + assert_eq!(amount_locked_actual, amount_locked_expected); + + // 6.2 Check signer key + let signer_key_expected = Value::buff_from(bob.public_key.to_bytes_compressed()).unwrap(); + let signer_key_actual = bob_tx_result_ok.data_map.get("signer-key").unwrap().clone(); + assert_eq!(signer_key_expected, signer_key_actual); + + // 6.3 Check unlock height (end of cycle 7 - block 140) + let unlock_height_expected = Value::UInt( + peer.config + .burnchain + .reward_cycle_to_block_height((next_reward_cycle + lock_period) as u64) + .wrapping_sub(1) as u128, + ); + let unlock_height_actual = bob_tx_result_ok + .data_map + .get("unlock-burn-height") + .unwrap() + .clone(); + assert_eq!(unlock_height_expected, unlock_height_actual); + + // Now starting create vote txs + // Fetch signer indices in reward cycle 6 + // Alice vote + let contract = " + (define-private (sample) + (from-consensus-buff? principal 0x062011deadbeef11ababffff11deadbeef11ababffff0461626364)) + (sample) + "; + + let tx_payload = TransactionPayload::new_smart_contract( + &format!("hello-world"), + &contract.to_string(), + Some(ClarityVersion::Clarity2), + ) + .unwrap(); + + let alice_tx = super::test::make_tx(&alice.private_key, alice.nonce, 1000, tx_payload); + alice.nonce += 1; + let alice_txid = alice_tx.txid(); + let txs = vec![alice_tx]; + + info!("Submitting block with test txs"); + + let e = tenure_with_txs_fallible(&mut peer, &txs, &mut peer_nonce, &mut test_signers) + .expect_err("Should not have produced a valid block with this tx"); + match e { + ChainstateError::ProblematicTransaction(txid) => { + assert_eq!(txid, alice_txid); + } + _ => panic!("Expected a problematic transaction result"), + } +} + // In this test two solo service signers, Alice & Bob, provide auth // for Carl & Dave, solo stackers. Alice provides a signature for Carl, // Bob uses 'set-signer-key...' for Dave. @@ -8510,7 +8861,7 @@ fn delegate_stack_increase_err(use_nakamoto: bool) { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - key_to_stacks_addr(bob_delegate_key).bytes, + key_to_stacks_addr(bob_delegate_key).destruct().1, ); let next_reward_cycle = 1 + burnchain @@ -8901,6 +9252,60 @@ pub fn prepare_pox4_test<'a>( } } +use crate::chainstate::stacks::Error as ChainstateError; +pub fn tenure_with_txs_fallible( + peer: &mut TestPeer, + txs: &[StacksTransaction], + coinbase_nonce: &mut usize, + test_signers: &mut Option, +) -> Result { + if let Some(test_signers) = test_signers { + let (burn_ops, mut tenure_change, miner_key) = + peer.begin_nakamoto_tenure(TenureChangeCause::BlockFound); + let (_, _, consensus_hash) = peer.next_burnchain_block(burn_ops.clone()); + let vrf_proof = peer.make_nakamoto_vrf_proof(miner_key); + + tenure_change.tenure_consensus_hash = consensus_hash.clone(); + tenure_change.burn_view_consensus_hash = consensus_hash.clone(); + + let tenure_change_tx = peer + .miner + .make_nakamoto_tenure_change(tenure_change.clone()); + let coinbase_tx = peer.miner.make_nakamoto_coinbase(None, vrf_proof); + + let blocks_and_sizes = peer.make_nakamoto_tenure_and( + tenure_change_tx, + coinbase_tx, + test_signers, + |_| {}, + |_miner, _chainstate, _sort_dbconn, _blocks| { + info!("Building nakamoto block. Blocks len {}", _blocks.len()); + if _blocks.is_empty() { + txs.to_vec() + } else { + vec![] + } + }, + |_| true, + )?; + let blocks: Vec<_> = blocks_and_sizes + .into_iter() + .map(|(block, _, _)| block) + .collect(); + + let chainstate = &mut peer.stacks_node.as_mut().unwrap().chainstate; + let sort_db = peer.sortdb.as_mut().unwrap(); + let latest_block = sort_db + .index_handle_at_tip() + .get_nakamoto_tip_block_id() + .unwrap() + .unwrap(); + Ok(latest_block) + } else { + Ok(peer.tenure_with_txs(txs, coinbase_nonce)) + } +} + pub fn tenure_with_txs( peer: &mut TestPeer, txs: &[StacksTransaction], @@ -9044,11 +9449,11 @@ fn missed_slots_no_unlock() { ); assert_eq!( reward_set_entries[0].reward_address.bytes(), - bob_address.bytes.0.to_vec() + bob_address.bytes().0.to_vec() ); assert_eq!( reward_set_entries[1].reward_address.bytes(), - alice_address.bytes.0.to_vec() + alice_address.bytes().0.to_vec() ); } @@ -9076,11 +9481,11 @@ fn missed_slots_no_unlock() { assert_eq!(reward_set_entries.len(), 2); assert_eq!( reward_set_entries[0].reward_address.bytes(), - bob_address.bytes.0.to_vec() + bob_address.bytes().0.to_vec() ); assert_eq!( reward_set_entries[1].reward_address.bytes(), - alice_address.bytes.0.to_vec() + alice_address.bytes().0.to_vec() ); } @@ -9173,7 +9578,7 @@ fn missed_slots_no_unlock() { assert_eq!(rewarded_addrs.len(), 1); assert_eq!( reward_set_data.reward_set.rewarded_addresses[0].bytes(), - alice_address.bytes.0.to_vec(), + alice_address.bytes().0.to_vec(), ); reward_cycles_in_2_5 += 1; eprintln!("{:?}", b.reward_set_data) @@ -9292,7 +9697,7 @@ fn no_lockups_2_5() { ); assert_eq!( reward_set_entries[0].reward_address.bytes(), - bob_address.bytes.0.to_vec() + bob_address.bytes().0.to_vec() ); } diff --git a/stackslib/src/chainstate/stacks/db/accounts.rs b/stackslib/src/chainstate/stacks/db/accounts.rs index eeacd95303..bf00b00b54 100644 --- a/stackslib/src/chainstate/stacks/db/accounts.rs +++ b/stackslib/src/chainstate/stacks/db/accounts.rs @@ -1219,10 +1219,7 @@ mod test { // dummy reward let mut tip_reward = make_dummy_miner_payment_schedule( - &StacksAddress { - version: 0, - bytes: Hash160([0u8; 20]), - }, + &StacksAddress::new(0, Hash160([0u8; 20])).unwrap(), 0, 0, 0, @@ -1294,10 +1291,7 @@ mod test { // dummy reward let mut tip_reward = make_dummy_miner_payment_schedule( - &StacksAddress { - version: 0, - bytes: Hash160([0u8; 20]), - }, + &StacksAddress::new(0, Hash160([0u8; 20])).unwrap(), 0, 0, 0, @@ -1344,10 +1338,7 @@ mod test { // dummy reward let mut tip_reward = make_dummy_miner_payment_schedule( - &StacksAddress { - version: 0, - bytes: Hash160([0u8; 20]), - }, + &StacksAddress::new(0, Hash160([0u8; 20])).unwrap(), 0, 0, 0, diff --git a/stackslib/src/chainstate/stacks/db/blocks.rs b/stackslib/src/chainstate/stacks/db/blocks.rs index 30b38c10cc..57a8091884 100644 --- a/stackslib/src/chainstate/stacks/db/blocks.rs +++ b/stackslib/src/chainstate/stacks/db/blocks.rs @@ -6860,7 +6860,7 @@ impl StacksChainState { // version byte matches? if !StacksChainState::is_valid_address_version( chainstate_config.mainnet, - address.version, + address.version(), ) { return Err(MemPoolRejection::BadAddressVersionByte); } diff --git a/stackslib/src/chainstate/stacks/db/mod.rs b/stackslib/src/chainstate/stacks/db/mod.rs index 6853ec0ee9..ed6b0ffb13 100644 --- a/stackslib/src/chainstate/stacks/db/mod.rs +++ b/stackslib/src/chainstate/stacks/db/mod.rs @@ -1226,7 +1226,7 @@ impl StacksChainState { fn parse_genesis_address(addr: &str, mainnet: bool) -> PrincipalData { // Typical entries are BTC encoded addresses that need converted to STX - let mut stacks_address = match LegacyBitcoinAddress::from_b58(&addr) { + let stacks_address = match LegacyBitcoinAddress::from_b58(&addr) { Ok(addr) => StacksAddress::from_legacy_bitcoin_address(&addr), // A few addresses (from legacy placeholder accounts) are already STX addresses _ => match StacksAddress::from_string(addr) { @@ -1236,20 +1236,25 @@ impl StacksChainState { }; // Convert a given address to the currently running network mode (mainnet vs testnet). // All addresses from the Stacks 1.0 import data should be mainnet, but we'll handle either case. - stacks_address.version = if mainnet { - match stacks_address.version { + let converted_version = if mainnet { + match stacks_address.version() { C32_ADDRESS_VERSION_TESTNET_SINGLESIG => C32_ADDRESS_VERSION_MAINNET_SINGLESIG, C32_ADDRESS_VERSION_TESTNET_MULTISIG => C32_ADDRESS_VERSION_MAINNET_MULTISIG, - _ => stacks_address.version, + _ => stacks_address.version(), } } else { - match stacks_address.version { + match stacks_address.version() { C32_ADDRESS_VERSION_MAINNET_SINGLESIG => C32_ADDRESS_VERSION_TESTNET_SINGLESIG, C32_ADDRESS_VERSION_MAINNET_MULTISIG => C32_ADDRESS_VERSION_TESTNET_MULTISIG, - _ => stacks_address.version, + _ => stacks_address.version(), } }; - let principal: PrincipalData = stacks_address.into(); + + let (_, bytes) = stacks_address.destruct(); + let principal: PrincipalData = StandardPrincipalData::new(converted_version, bytes.0) + .expect("FATAL: infallible constant version byte is not valid") + .into(); + return principal; } diff --git a/stackslib/src/chainstate/stacks/db/transactions.rs b/stackslib/src/chainstate/stacks/db/transactions.rs index 88bbf73dfe..3758f8f4e6 100644 --- a/stackslib/src/chainstate/stacks/db/transactions.rs +++ b/stackslib/src/chainstate/stacks/db/transactions.rs @@ -1414,7 +1414,6 @@ impl StacksChainState { Ok(receipt) } TransactionPayload::Coinbase(..) => { - // no-op; not handled here // NOTE: technically, post-conditions are allowed (even if they're non-sensical). let receipt = StacksTransactionReceipt::from_coinbase(tx.clone()); @@ -1605,11 +1604,25 @@ pub mod test { epoch_id: StacksEpochId::Epoch21, ast_rules: ASTRules::PrecheckSize, }; + pub const TestBurnStateDB_25: UnitTestBurnStateDB = UnitTestBurnStateDB { + epoch_id: StacksEpochId::Epoch25, + ast_rules: ASTRules::PrecheckSize, + }; + pub const TestBurnStateDB_30: UnitTestBurnStateDB = UnitTestBurnStateDB { + epoch_id: StacksEpochId::Epoch30, + ast_rules: ASTRules::PrecheckSize, + }; + pub const TestBurnStateDB_31: UnitTestBurnStateDB = UnitTestBurnStateDB { + epoch_id: StacksEpochId::Epoch31, + ast_rules: ASTRules::PrecheckSize, + }; pub const ALL_BURN_DBS: &[&dyn BurnStateDB] = &[ &TestBurnStateDB_20 as &dyn BurnStateDB, &TestBurnStateDB_2_05 as &dyn BurnStateDB, &TestBurnStateDB_21 as &dyn BurnStateDB, + &TestBurnStateDB_30 as &dyn BurnStateDB, + &TestBurnStateDB_31 as &dyn BurnStateDB, ]; pub const PRE_21_DBS: &[&dyn BurnStateDB] = &[ @@ -1617,6 +1630,11 @@ pub mod test { &TestBurnStateDB_2_05 as &dyn BurnStateDB, ]; + pub const NAKAMOTO_DBS: &[&dyn BurnStateDB] = &[ + &TestBurnStateDB_30 as &dyn BurnStateDB, + &TestBurnStateDB_31 as &dyn BurnStateDB, + ]; + #[test] fn contract_publish_runtime_error() { let contract_id = QualifiedContractIdentifier::local("contract").unwrap(); @@ -1703,10 +1721,7 @@ pub mod test { .unwrap(); let auth = TransactionAuth::from_p2pkh(&privk).unwrap(); let addr = auth.origin().address_testnet(); - let recv_addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let recv_addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut tx_stx_transfer = StacksTransaction::new( TransactionVersion::Testnet, @@ -1770,11 +1785,7 @@ pub mod test { let auth = TransactionAuth::from_p2pkh(&privk).unwrap(); let recv_addr = PrincipalData::from(QualifiedContractIdentifier { - issuer: StacksAddress { - version: 1, - bytes: Hash160([0xfe; 20]), - } - .into(), + issuer: StacksAddress::new(1, Hash160([0xfe; 20])).unwrap().into(), name: "contract-hellow".into(), }); @@ -2046,10 +2057,7 @@ pub mod test { let addr = auth.origin().address_testnet(); let addr_sponsor = auth.sponsor().unwrap().address_testnet(); - let recv_addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let recv_addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut tx_stx_transfer = StacksTransaction::new( TransactionVersion::Testnet, @@ -2380,7 +2388,7 @@ pub mod test { // Verify that the syntax error is recorded in the receipt let expected_error = - if burn_db.get_stacks_epoch(0).unwrap().epoch_id == StacksEpochId::Epoch21 { + if burn_db.get_stacks_epoch(0).unwrap().epoch_id >= StacksEpochId::Epoch21 { expected_errors_2_1[i].to_string() } else { expected_errors[i].to_string() @@ -5046,14 +5054,8 @@ pub mod test { let auth = TransactionAuth::from_p2pkh(&privk).unwrap(); let addr = auth.origin().address_testnet(); let origin = addr.to_account_principal(); - let recv_addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; - let contract_addr = StacksAddress { - version: 1, - bytes: Hash160([0x01; 20]), - }; + let recv_addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); + let contract_addr = StacksAddress::new(1, Hash160([0x01; 20])).unwrap(); let asset_info_1 = AssetInfo { contract_address: contract_addr.clone(), @@ -6898,14 +6900,8 @@ pub mod test { let auth = TransactionAuth::from_p2pkh(&privk).unwrap(); let addr = auth.origin().address_testnet(); let origin = addr.to_account_principal(); - let _recv_addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; - let contract_addr = StacksAddress { - version: 1, - bytes: Hash160([0x01; 20]), - }; + let _recv_addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); + let contract_addr = StacksAddress::new(1, Hash160([0x01; 20])).unwrap(); let asset_info = AssetInfo { contract_address: contract_addr.clone(), @@ -7252,10 +7248,7 @@ pub mod test { let auth = TransactionAuth::from_p2pkh(&privk).unwrap(); let addr = auth.origin().address_testnet(); let origin = addr.to_account_principal(); - let _recv_addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let _recv_addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); // stx-transfer for 123 microstx let mut stx_asset_map = AssetMap::new(); @@ -8748,10 +8741,7 @@ pub mod test { .unwrap(); let auth = TransactionAuth::from_p2pkh(&privk).unwrap(); let addr = auth.origin().address_testnet(); - let recv_addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let recv_addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let smart_contract = StacksTransaction::new( TransactionVersion::Testnet, @@ -8962,10 +8952,7 @@ pub mod test { .unwrap(); let auth = TransactionAuth::from_p2pkh(&privk).unwrap(); let addr = auth.origin().address_testnet(); - let recv_addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let recv_addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let smart_contract = StacksTransaction::new( TransactionVersion::Testnet, @@ -11401,4 +11388,438 @@ pub mod test { conn.commit_block(); } + + /// Verify that transactions with bare PrincipalDatas in them cannot decode if the version byte + /// is inappropriate. + #[test] + fn test_invalid_address_prevents_tx_decode() { + // token transfer + let bad_payload_bytes = vec![ + TransactionPayloadID::TokenTransfer as u8, + // Clarity value type (StandardPrincipalData) + 0x05, + // bad address (version byte 32) + 0x20, + // address body (0x00000000000000000000) + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + // amount (1 uSTX) + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + // memo + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + 0x11, + ]; + + let mut good_payload_bytes = bad_payload_bytes.clone(); + + // only diff is the address version + good_payload_bytes[2] = 0x1f; + + let bad_payload: Result = + TransactionPayload::consensus_deserialize(&mut &bad_payload_bytes[..]); + assert!(bad_payload.is_err()); + + let _: TransactionPayload = + TransactionPayload::consensus_deserialize(&mut &good_payload_bytes[..]).unwrap(); + + // contract-call with bad contract address + let bad_payload_bytes = vec![ + TransactionPayloadID::ContractCall as u8, + // Stacks address + // bad version byte + 0x20, + // address body (0x00000000000000000000) + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + // contract name ("hello") + 0x05, + 0x68, + 0x65, + 0x6c, + 0x6c, + 0x6f, + // function name ("world") + 0x05, + 0x77, + 0x6f, + 0x72, + 0x6c, + 0x64, + // arguments (good address) + // length (1) + 0x00, + 0x00, + 0x00, + 0x01, + // StandardPrincipalData + 0x05, + // address version (1) + 0x01, + // address body (0x00000000000000000000) + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ]; + + let mut good_payload_bytes = bad_payload_bytes.clone(); + + // only diff is the address version + good_payload_bytes[1] = 0x1f; + + let bad_payload: Result = + TransactionPayload::consensus_deserialize(&mut &bad_payload_bytes[..]); + assert!(bad_payload.is_err()); + + let _: TransactionPayload = + TransactionPayload::consensus_deserialize(&mut &good_payload_bytes[..]).unwrap(); + + // contract-call with bad Principal argument + let bad_payload_bytes = vec![ + TransactionPayloadID::ContractCall as u8, + // Stacks address + 0x01, + // address body (0x00000000000000000000) + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + // contract name ("hello") + 0x05, + 0x68, + 0x65, + 0x6c, + 0x6c, + 0x6f, + // function name ("world") + 0x05, + 0x77, + 0x6f, + 0x72, + 0x6c, + 0x64, + // arguments (good address) + // length (1) + 0x00, + 0x00, + 0x00, + 0x01, + // StandardPrincipalData + 0x05, + // address version (32 -- bad) + 0x20, + // address body (0x00000000000000000000) + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ]; + + let mut good_payload_bytes = bad_payload_bytes.clone(); + good_payload_bytes[39] = 0x1f; + + let bad_payload: Result = + TransactionPayload::consensus_deserialize(&mut &bad_payload_bytes[..]); + assert!(bad_payload.is_err()); + + let _: TransactionPayload = + TransactionPayload::consensus_deserialize(&mut &good_payload_bytes[..]).unwrap(); + + let bad_payload_bytes = vec![ + // payload type ID + TransactionPayloadID::NakamotoCoinbase as u8, + // buffer + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + 0x12, + // have contract recipient, so Some(..) + 0x0a, + // contract address type + 0x06, + // address (bad version) + 0x20, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + // name length + 0x0c, + // name ('foo-contract') + 0x66, + 0x6f, + 0x6f, + 0x2d, + 0x63, + 0x6f, + 0x6e, + 0x74, + 0x72, + 0x61, + 0x63, + 0x74, + // proof bytes + 0x92, + 0x75, + 0xdf, + 0x67, + 0xa6, + 0x8c, + 0x87, + 0x45, + 0xc0, + 0xff, + 0x97, + 0xb4, + 0x82, + 0x01, + 0xee, + 0x6d, + 0xb4, + 0x47, + 0xf7, + 0xc9, + 0x3b, + 0x23, + 0xae, + 0x24, + 0xcd, + 0xc2, + 0x40, + 0x0f, + 0x52, + 0xfd, + 0xb0, + 0x8a, + 0x1a, + 0x6a, + 0xc7, + 0xec, + 0x71, + 0xbf, + 0x9c, + 0x9c, + 0x76, + 0xe9, + 0x6e, + 0xe4, + 0x67, + 0x5e, + 0xbf, + 0xf6, + 0x06, + 0x25, + 0xaf, + 0x28, + 0x71, + 0x85, + 0x01, + 0x04, + 0x7b, + 0xfd, + 0x87, + 0xb8, + 0x10, + 0xc2, + 0xd2, + 0x13, + 0x9b, + 0x73, + 0xc2, + 0x3b, + 0xd6, + 0x9d, + 0xe6, + 0x63, + 0x60, + 0x95, + 0x3a, + 0x64, + 0x2c, + 0x2a, + 0x33, + 0x0a, + ]; + + let mut good_payload_bytes = bad_payload_bytes.clone(); + debug!( + "index is {:?}", + good_payload_bytes.iter().find(|x| **x == 0x20) + ); + good_payload_bytes[35] = 0x1f; + + let bad_payload: Result = + TransactionPayload::consensus_deserialize(&mut &bad_payload_bytes[..]); + assert!(bad_payload.is_err()); + + let _: TransactionPayload = + TransactionPayload::consensus_deserialize(&mut &good_payload_bytes[..]).unwrap(); + } } diff --git a/stackslib/src/chainstate/stacks/mod.rs b/stackslib/src/chainstate/stacks/mod.rs index 23990fe199..7afc464ebe 100644 --- a/stackslib/src/chainstate/stacks/mod.rs +++ b/stackslib/src/chainstate/stacks/mod.rs @@ -669,8 +669,7 @@ pub struct TransactionContractCall { impl TransactionContractCall { pub fn contract_identifier(&self) -> QualifiedContractIdentifier { - let standard_principal = - StandardPrincipalData(self.address.version, self.address.bytes.0.clone()); + let standard_principal = StandardPrincipalData::from(self.address.clone()); QualifiedContractIdentifier::new(standard_principal, self.contract_name.clone()) } } @@ -1126,10 +1125,7 @@ pub mod test { post_condition_mode: &TransactionPostConditionMode, epoch_id: StacksEpochId, ) -> Vec { - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let asset_name = ClarityName::try_from("hello-asset").unwrap(); let asset_value = Value::buff_from(vec![0, 1, 2, 3]).unwrap(); let contract_name = ContractName::try_from("hello-world").unwrap(); @@ -1276,15 +1272,9 @@ pub mod test { let tx_post_condition_principals = vec![ PostConditionPrincipal::Origin, - PostConditionPrincipal::Standard(StacksAddress { - version: 1, - bytes: Hash160([1u8; 20]), - }), + PostConditionPrincipal::Standard(StacksAddress::new(1, Hash160([1u8; 20])).unwrap()), PostConditionPrincipal::Contract( - StacksAddress { - version: 2, - bytes: Hash160([2u8; 20]), - }, + StacksAddress::new(2, Hash160([2u8; 20])).unwrap(), ContractName::try_from("hello-world").unwrap(), ), ]; @@ -1403,10 +1393,7 @@ pub mod test { ]); } - let stx_address = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let stx_address = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let proof_bytes = hex_bytes("9275df67a68c8745c0ff97b48201ee6db447f7c93b23ae24cdc2400f52fdb08a1a6ac7ec71bf9c9c76e96ee4675ebff60625af28718501047bfd87b810c2d2139b73c23bd69de66360953a642c2a330a").unwrap(); let proof = VRFProof::from_bytes(&proof_bytes[..].to_vec()).unwrap(); let mut tx_payloads = vec![ @@ -1424,10 +1411,7 @@ pub mod test { TokenTransferMemo([0u8; 34]), ), TransactionPayload::ContractCall(TransactionContractCall { - address: StacksAddress { - version: 4, - bytes: Hash160([0xfc; 20]), - }, + address: StacksAddress::new(4, Hash160([0xfc; 20])).unwrap(), contract_name: ContractName::try_from("hello-contract-name").unwrap(), function_name: ClarityName::try_from("hello-contract-call").unwrap(), function_args: vec![Value::Int(0)], @@ -1481,9 +1465,9 @@ pub mod test { ), TransactionPayload::Coinbase( CoinbasePayload([0x12; 32]), - Some(PrincipalData::Standard(StandardPrincipalData( - 0x01, [0x02; 20], - ))), + Some(PrincipalData::Standard( + StandardPrincipalData::new(0x01, [0x02; 20]).unwrap(), + )), Some(proof.clone()), ), ]) @@ -1499,9 +1483,9 @@ pub mod test { ), TransactionPayload::Coinbase( CoinbasePayload([0x12; 32]), - Some(PrincipalData::Standard(StandardPrincipalData( - 0x01, [0x02; 20], - ))), + Some(PrincipalData::Standard( + StandardPrincipalData::new(0x01, [0x02; 20]).unwrap(), + )), None, ), ]) @@ -1649,10 +1633,7 @@ pub mod test { ) .unwrap(); - let stx_address = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let stx_address = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let payload = TransactionPayload::TokenTransfer( stx_address.into(), 123, diff --git a/stackslib/src/chainstate/stacks/tests/chain_histories.rs b/stackslib/src/chainstate/stacks/tests/chain_histories.rs index 6d102af8ec..2409214048 100644 --- a/stackslib/src/chainstate/stacks/tests/chain_histories.rs +++ b/stackslib/src/chainstate/stacks/tests/chain_histories.rs @@ -2846,7 +2846,8 @@ pub fn mine_invalid_token_transfers_block( .try_mine_tx(clarity_tx, &tx_coinbase_signed, ASTRules::PrecheckSize) .unwrap(); - let recipient = StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160([0xff; 20])); + let recipient = + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160([0xff; 20])).unwrap(); let tx1 = make_token_transfer( miner, burnchain_height, diff --git a/stackslib/src/chainstate/stacks/transaction.rs b/stackslib/src/chainstate/stacks/transaction.rs index c0fa7f1727..44a5701012 100644 --- a/stackslib/src/chainstate/stacks/transaction.rs +++ b/stackslib/src/chainstate/stacks/transaction.rs @@ -20,7 +20,10 @@ use std::io::{Read, Write}; use clarity::vm::representations::{ClarityName, ContractName}; use clarity::vm::types::serialization::SerializationError as clarity_serialization_error; -use clarity::vm::types::{QualifiedContractIdentifier, StandardPrincipalData}; +use clarity::vm::types::{ + QualifiedContractIdentifier, SequenceData, SequencedValue, StandardPrincipalData, + MAX_TYPE_DEPTH, +}; use clarity::vm::{ClarityVersion, SymbolicExpression, SymbolicExpressionType, Value}; use stacks_common::codec::{read_next, write_next, Error as codec_error, StacksMessageCodec}; use stacks_common::types::chainstate::StacksAddress; @@ -1851,10 +1854,7 @@ mod test { ), TransactionPayload::SmartContract(..) => { TransactionPayload::ContractCall(TransactionContractCall { - address: StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }, + address: StacksAddress::new(1, Hash160([0xff; 20])).unwrap(), contract_name: ContractName::try_from("hello-world").unwrap(), function_name: ClarityName::try_from("hello-function").unwrap(), function_args: vec![Value::Int(0)], @@ -1959,10 +1959,7 @@ mod test { #[test] fn tx_stacks_transaction_payload_tokens() { - let addr = PrincipalData::from(StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }); + let addr = PrincipalData::from(StacksAddress::new(1, Hash160([0xff; 20])).unwrap()); let tt_stx = TransactionPayload::TokenTransfer(addr.clone(), 123, TokenTransferMemo([1u8; 34])); @@ -1977,11 +1974,7 @@ mod test { check_codec_and_corruption::(&tt_stx, &tt_stx_bytes); let addr = PrincipalData::from(QualifiedContractIdentifier { - issuer: StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - } - .into(), + issuer: StacksAddress::new(1, Hash160([0xff; 20])).unwrap().into(), name: "foo-contract".into(), }); @@ -2006,10 +1999,7 @@ mod test { let hello_contract_body = "hello contract code body"; let contract_call = TransactionContractCall { - address: StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }, + address: StacksAddress::new(1, Hash160([0xff; 20])).unwrap(), contract_name: ContractName::try_from(hello_contract_name).unwrap(), function_name: ClarityName::try_from(hello_function_name).unwrap(), function_args: vec![Value::Int(0)], @@ -2304,11 +2294,7 @@ mod test { let proof = VRFProof::from_bytes(&proof_bytes[..].to_vec()).unwrap(); let recipient = PrincipalData::from(QualifiedContractIdentifier { - issuer: StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - } - .into(), + issuer: StacksAddress::new(1, Hash160([0xff; 20])).unwrap().into(), name: "foo-contract".into(), }); @@ -3366,10 +3352,7 @@ mod test { let hello_function_name = "hello-function-name"; let contract_call = TransactionContractCall { - address: StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }, + address: StacksAddress::new(1, Hash160([0xff; 20])).unwrap(), contract_name: ContractName::try_from(hello_contract_name).unwrap(), function_name: ClarityName::try_from(hello_function_name).unwrap(), function_args: vec![Value::Int(0)], @@ -3408,10 +3391,7 @@ mod test { #[test] fn tx_stacks_transaction_payload_invalid_contract_name() { // test invalid contract name - let address = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let address = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let contract_name = "hello\x00contract-name"; let function_name = ClarityName::try_from("hello-function-name").unwrap(); let function_args = vec![Value::Int(0)]; @@ -3447,10 +3427,7 @@ mod test { #[test] fn tx_stacks_transaction_payload_invalid_function_name() { // test invalid contract name - let address = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let address = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let contract_name = ContractName::try_from("hello-contract-name").unwrap(); let hello_function_name = "hello\x00function-name"; let mut hello_function_name_bytes = vec![hello_function_name.len() as u8]; @@ -3484,10 +3461,7 @@ mod test { #[test] fn tx_stacks_asset() { - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let addr_bytes = [ // version 0x01, // bytes @@ -3536,24 +3510,15 @@ mod test { fn tx_stacks_postcondition() { let tx_post_condition_principals = vec![ PostConditionPrincipal::Origin, - PostConditionPrincipal::Standard(StacksAddress { - version: 1, - bytes: Hash160([1u8; 20]), - }), + PostConditionPrincipal::Standard(StacksAddress::new(1, Hash160([1u8; 20])).unwrap()), PostConditionPrincipal::Contract( - StacksAddress { - version: 2, - bytes: Hash160([2u8; 20]), - }, + StacksAddress::new(2, Hash160([2u8; 20])).unwrap(), ContractName::try_from("hello-world").unwrap(), ), ]; for tx_pcp in tx_post_condition_principals { - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let asset_name = ClarityName::try_from("hello-asset").unwrap(); let contract_name = ContractName::try_from("contract-name").unwrap(); @@ -3659,10 +3624,7 @@ mod test { #[test] fn tx_stacks_postcondition_invalid() { - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let asset_name = ClarityName::try_from("hello-asset").unwrap(); let contract_name = ContractName::try_from("hello-world").unwrap(); @@ -3892,10 +3854,7 @@ mod test { let asset_value = StacksString::from_str("asset-value").unwrap(); - let contract_addr = StacksAddress { - version: 2, - bytes: Hash160([0xfe; 20]), - }; + let contract_addr = StacksAddress::new(2, Hash160([0xfe; 20])).unwrap(); let asset_info = AssetInfo { contract_address: contract_addr.clone(), @@ -3903,10 +3862,7 @@ mod test { asset_name: asset_name.clone(), }; - let stx_address = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let stx_address = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let tx_contract_call = StacksTransaction::new( TransactionVersion::Mainnet, @@ -4191,10 +4147,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("143e543243dfcd8c02a12ad7ea371bd07bc91df9").unwrap() - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("143e543243dfcd8c02a12ad7ea371bd07bc91df9").unwrap() + ) + .unwrap(), ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -4227,7 +4184,7 @@ mod test { signed_tx.auth { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } else { panic!(); } @@ -4265,25 +4222,28 @@ mod test { let origin_address = auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("143e543243dfcd8c02a12ad7ea371bd07bc91df9").unwrap() - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("143e543243dfcd8c02a12ad7ea371bd07bc91df9").unwrap() + ) + .unwrap(), ); let sponsor_address = auth.sponsor().unwrap().address_mainnet(); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap(), ); - let diff_sponsor_address = StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("a139de6733cef9e4663c4a093c1a7390a1dcc297").unwrap(), - }; + let diff_sponsor_address = StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("a139de6733cef9e4663c4a093c1a7390a1dcc297").unwrap(), + ) + .unwrap(); let txs = tx_stacks_transaction_test_txs(&auth); @@ -4344,7 +4304,7 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } @@ -4354,7 +4314,7 @@ mod test { data.key_encoding, TransactionPublicKeyEncoding::Uncompressed ); // not what the origin would have seen - assert_eq!(data.signer, diff_sponsor_address.bytes); + assert_eq!(data.signer, *diff_sponsor_address.bytes()); // not what the origin would have seen } _ => assert!(false), @@ -4384,10 +4344,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("693cd53eb47d4749762d7cfaf46902bda5be5f97").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("693cd53eb47d4749762d7cfaf46902bda5be5f97").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -4423,7 +4384,7 @@ mod test { data.key_encoding, TransactionPublicKeyEncoding::Uncompressed ); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } else { panic!(); } @@ -4467,17 +4428,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("693cd53eb47d4749762d7cfaf46902bda5be5f97").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("693cd53eb47d4749762d7cfaf46902bda5be5f97").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -4529,7 +4492,7 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } @@ -4539,7 +4502,7 @@ mod test { data.key_encoding, TransactionPublicKeyEncoding::Uncompressed ); - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); } _ => assert!(false), } @@ -4582,10 +4545,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -4619,7 +4583,7 @@ mod test { if let TransactionAuth::Standard(TransactionSpendingCondition::Multisig(data)) = &signed_tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -4689,17 +4653,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -4753,13 +4719,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::Multisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -4817,10 +4783,11 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -4857,7 +4824,7 @@ mod test { if let TransactionAuth::Standard(TransactionSpendingCondition::Multisig(data)) = &signed_tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -4928,17 +4895,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -4991,13 +4960,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::Multisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -5054,10 +5023,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("2136367c9c740e7dbed8795afdf8a6d273096718").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("2136367c9c740e7dbed8795afdf8a6d273096718").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -5091,7 +5061,7 @@ mod test { if let TransactionAuth::Standard(TransactionSpendingCondition::Multisig(data)) = &signed_tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); @@ -5162,17 +5132,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("2136367c9c740e7dbed8795afdf8a6d273096718").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("2136367c9c740e7dbed8795afdf8a6d273096718").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -5226,13 +5198,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::Multisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); @@ -5275,10 +5247,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("f15fa5c59d14ffcb615fa6153851cd802bb312d2").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("f15fa5c59d14ffcb615fa6153851cd802bb312d2").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -5310,7 +5283,7 @@ mod test { if let TransactionAuth::Standard(TransactionSpendingCondition::Singlesig(data)) = &signed_tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); } else { panic!(); @@ -5354,17 +5327,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("f15fa5c59d14ffcb615fa6153851cd802bb312d2").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("f15fa5c59d14ffcb615fa6153851cd802bb312d2").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -5415,13 +5390,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::Singlesig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); } _ => assert!(false), @@ -5465,10 +5440,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -5503,7 +5479,7 @@ mod test { if let TransactionAuth::Standard(TransactionSpendingCondition::Multisig(data)) = &signed_tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -5574,17 +5550,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -5639,13 +5617,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::Multisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -5702,10 +5680,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -5736,7 +5715,7 @@ mod test { TransactionSpendingCondition::OrderIndependentMultisig(data), ) = &tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_public_key()); assert!(data.fields[1].is_signature()); @@ -5789,10 +5768,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -5826,7 +5806,7 @@ mod test { TransactionSpendingCondition::OrderIndependentMultisig(data), ) = &tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -5900,17 +5880,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -5972,13 +5954,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::OrderIndependentMultisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -6035,10 +6017,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -6071,7 +6054,7 @@ mod test { TransactionSpendingCondition::OrderIndependentMultisig(data), ) = &tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_public_key()); assert!(data.fields[1].is_signature()); @@ -6142,17 +6125,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -6214,13 +6199,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::OrderIndependentMultisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -6277,10 +6262,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -6313,7 +6299,7 @@ mod test { TransactionSpendingCondition::OrderIndependentMultisig(data), ) = &tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); @@ -6406,10 +6392,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("315d672961ef2583faf4107ab4ec5566014c867c").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("315d672961ef2583faf4107ab4ec5566014c867c").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -6451,7 +6438,7 @@ mod test { TransactionSpendingCondition::OrderIndependentMultisig(data), ) = &tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 9); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); @@ -6537,17 +6524,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -6609,13 +6598,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::OrderIndependentMultisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); @@ -6706,17 +6695,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("fc29d14be615b0f72a66b920040c2b5b8124990b").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("fc29d14be615b0f72a66b920040c2b5b8124990b").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -6792,13 +6783,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::OrderIndependentMultisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 5); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -6868,10 +6859,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -6905,7 +6897,7 @@ mod test { TransactionSpendingCondition::OrderIndependentMultisig(data), ) = &tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); @@ -6980,10 +6972,11 @@ mod test { let origin_address = origin_auth.origin().address_mainnet(); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("e2a4ae14ffb0a4a0982a06d07b97d57268d2bf94").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("e2a4ae14ffb0a4a0982a06d07b97d57268d2bf94").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -7026,7 +7019,7 @@ mod test { TransactionSpendingCondition::OrderIndependentMultisig(data), ) = &tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 6); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); @@ -7109,17 +7102,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -7182,13 +7177,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::OrderIndependentMultisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); @@ -7291,17 +7286,19 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("e3001c2b12f24ba279116d7001e3bd82b2b5eab4").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("e3001c2b12f24ba279116d7001e3bd82b2b5eab4").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -7368,13 +7365,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::OrderIndependentMultisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 7); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); @@ -7451,10 +7448,11 @@ mod test { assert_eq!(origin_address, order_independent_origin_address); assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -7488,7 +7486,7 @@ mod test { if let TransactionAuth::Standard(TransactionSpendingCondition::Multisig(data)) = &signed_tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -7536,7 +7534,7 @@ mod test { TransactionSpendingCondition::OrderIndependentMultisig(data), ) = &order_independent_tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_public_key()); assert!(data.fields[1].is_signature()); @@ -7601,10 +7599,11 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -7644,7 +7643,7 @@ mod test { if let TransactionAuth::Standard(TransactionSpendingCondition::Multisig(data)) = &signed_tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -7694,7 +7693,7 @@ mod test { TransactionSpendingCondition::OrderIndependentMultisig(data), ) = &tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_public_key()); assert!(data.fields[1].is_signature()); @@ -7759,10 +7758,11 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&origin_auth); @@ -7798,7 +7798,7 @@ mod test { if let TransactionAuth::Standard(TransactionSpendingCondition::Multisig(data)) = &signed_tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -7849,7 +7849,7 @@ mod test { TransactionSpendingCondition::OrderIndependentMultisig(data), ) = &tx.auth { - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); @@ -7928,18 +7928,20 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!(sponsor_address, order_independent_sponsor_address); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("a23ea89d6529ac48ac766f720e480beec7f19273").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -7994,13 +7996,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::Multisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -8086,13 +8088,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::OrderIndependentMultisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -8175,19 +8177,21 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!(sponsor_address, order_independent_sponsor_address); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("73a8b4a751a678fe83e9d35ce301371bb3d397f7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -8250,13 +8254,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::OrderIndependentMultisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -8342,13 +8346,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::OrderIndependentMultisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -8431,19 +8435,21 @@ mod test { assert_eq!( origin_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_hex("3597aaa4bde720be93e3829aae24e76e7fcdfd3e").unwrap(), + ) + .unwrap() ); assert_eq!(sponsor_address, order_independent_sponsor_address); assert_eq!( sponsor_address, - StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_MULTISIG, - bytes: Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), - } + StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_MULTISIG, + Hash160::from_hex("f5cfb61a07fb41a32197da01ce033888f0fe94a7").unwrap(), + ) + .unwrap() ); let txs = tx_stacks_transaction_test_txs(&auth); @@ -8499,13 +8505,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::Multisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_signature()); @@ -8592,13 +8598,13 @@ mod test { match origin { TransactionSpendingCondition::Singlesig(ref data) => { assert_eq!(data.key_encoding, TransactionPublicKeyEncoding::Compressed); - assert_eq!(data.signer, origin_address.bytes); + assert_eq!(data.signer, *origin_address.bytes()); } _ => assert!(false), } match sponsor { TransactionSpendingCondition::OrderIndependentMultisig(ref data) => { - assert_eq!(data.signer, sponsor_address.bytes); + assert_eq!(data.signer, *sponsor_address.bytes()); assert_eq!(data.fields.len(), 3); assert!(data.fields[0].is_signature()); assert!(data.fields[1].is_public_key()); diff --git a/stackslib/src/config/chain_data.rs b/stackslib/src/config/chain_data.rs index e4c3899511..b05871522b 100644 --- a/stackslib/src/config/chain_data.rs +++ b/stackslib/src/config/chain_data.rs @@ -794,13 +794,14 @@ EOF ] ), PoxAddress::Standard( - StacksAddress { - version: 20, - bytes: Hash160([ + StacksAddress::new( + 20, + Hash160([ 0x18, 0xc4, 0x20, 0x80, 0xa1, 0xe8, 0x7f, 0xd0, 0x2d, 0xd3, 0xfc, 0xa9, 0x4c, 0x45, 0x13, 0xf9, 0xec, 0xfe, 0x74, 0x14 ]) - }, + ) + .unwrap(), None ) ] diff --git a/stackslib/src/core/tests/mod.rs b/stackslib/src/core/tests/mod.rs index dccf7fb8c3..c7fe269d31 100644 --- a/stackslib/src/core/tests/mod.rs +++ b/stackslib/src/core/tests/mod.rs @@ -215,14 +215,9 @@ fn mempool_walk_over_fork() { let block = &blocks_to_broadcast_in[ix]; let good_tx = &txs[ix]; - let origin_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&[ix as u8; 32]), - }; - let sponsor_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&[0x80 | (ix as u8); 32]), - }; + let origin_address = StacksAddress::new(22, Hash160::from_data(&[ix as u8; 32])).unwrap(); + let sponsor_address = + StacksAddress::new(22, Hash160::from_data(&[0x80 | (ix as u8); 32])).unwrap(); let txid = good_tx.txid(); let tx_bytes = good_tx.serialize_to_vec(); @@ -469,14 +464,8 @@ fn mempool_walk_over_fork() { let mut mempool_tx = mempool.tx_begin().unwrap(); let block = &b_1; let tx = &txs[1]; - let origin_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&[1; 32]), - }; - let sponsor_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&[0x81; 32]), - }; + let origin_address = StacksAddress::new(22, Hash160::from_data(&[1; 32])).unwrap(); + let sponsor_address = StacksAddress::new(22, Hash160::from_data(&[0x81; 32])).unwrap(); let txid = tx.txid(); let tx_bytes = tx.serialize_to_vec(); @@ -523,14 +512,8 @@ fn mempool_walk_over_fork() { let mut mempool_tx = mempool.tx_begin().unwrap(); let block = &b_4; let tx = &txs[1]; - let origin_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&[0; 32]), - }; - let sponsor_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&[1; 32]), - }; + let origin_address = StacksAddress::new(22, Hash160::from_data(&[0; 32])).unwrap(); + let sponsor_address = StacksAddress::new(22, Hash160::from_data(&[1; 32])).unwrap(); let txid = tx.txid(); let tx_bytes = tx.serialize_to_vec(); @@ -1307,14 +1290,8 @@ fn mempool_do_not_replace_tx() { let mut mempool_tx = mempool.tx_begin().unwrap(); // do an initial insert - let origin_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&[0; 32]), - }; - let sponsor_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&[1; 32]), - }; + let origin_address = StacksAddress::new(22, Hash160::from_data(&[0; 32])).unwrap(); + let sponsor_address = StacksAddress::new(22, Hash160::from_data(&[1; 32])).unwrap(); tx.set_tx_fee(123); @@ -1411,14 +1388,9 @@ fn mempool_db_load_store_replace_tx(#[case] behavior: MempoolCollectionBehavior) eprintln!("add all txs"); for (i, mut tx) in txs.into_iter().enumerate() { // make sure each address is unique per tx (not the case in codec_all_transactions) - let origin_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&i.to_be_bytes()), - }; - let sponsor_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&(i + 1).to_be_bytes()), - }; + let origin_address = StacksAddress::new(22, Hash160::from_data(&i.to_be_bytes())).unwrap(); + let sponsor_address = + StacksAddress::new(22, Hash160::from_data(&(i + 1).to_be_bytes())).unwrap(); tx.set_tx_fee(123); @@ -1668,10 +1640,7 @@ fn mempool_db_test_rbf() { tx_fee: 456, signature: MessageSignature::from_raw(&[0xff; 65]), }); - let stx_address = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let stx_address = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let payload = TransactionPayload::TokenTransfer( PrincipalData::from(QualifiedContractIdentifier { issuer: stx_address.into(), @@ -1691,14 +1660,9 @@ fn mempool_db_test_rbf() { }; let i: usize = 0; - let origin_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&i.to_be_bytes()), - }; - let sponsor_address = StacksAddress { - version: 22, - bytes: Hash160::from_data(&(i + 1).to_be_bytes()), - }; + let origin_address = StacksAddress::new(22, Hash160::from_data(&i.to_be_bytes())).unwrap(); + let sponsor_address = + StacksAddress::new(22, Hash160::from_data(&(i + 1).to_be_bytes())).unwrap(); tx.set_tx_fee(123); let txid = tx.txid(); @@ -1807,10 +1771,7 @@ fn test_add_txs_bloom_filter() { let chainstate_path = chainstate_path(function_name!()); let mut mempool = MemPoolDB::open_test(false, 0x80000000, &chainstate_path).unwrap(); - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut all_txids: Vec> = vec![]; @@ -1916,10 +1877,7 @@ fn test_txtags() { let chainstate_path = chainstate_path(function_name!()); let mut mempool = MemPoolDB::open_test(false, 0x80000000, &chainstate_path).unwrap(); - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut seed = [0u8; 32]; thread_rng().fill_bytes(&mut seed); @@ -2015,10 +1973,7 @@ fn test_make_mempool_sync_data() { let chainstate_path = chainstate_path(function_name!()); let mut mempool = MemPoolDB::open_test(false, 0x80000000, &chainstate_path).unwrap(); - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut txids = vec![]; let mut nonrecent_fp_rates = vec![]; @@ -2192,10 +2147,7 @@ fn test_find_next_missing_transactions() { let chainstate_path = chainstate_path(function_name!()); let mut mempool = MemPoolDB::open_test(false, 0x80000000, &chainstate_path).unwrap(); - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let block_height = 10; let mut txids = vec![]; @@ -2463,10 +2415,7 @@ fn test_drop_and_blacklist_txs_by_time() { let chainstate_path = chainstate_path(function_name!()); let mut mempool = MemPoolDB::open_test(false, 0x80000000, &chainstate_path).unwrap(); - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut txs = vec![]; let block_height = 10; @@ -2583,10 +2532,7 @@ fn test_drop_and_blacklist_txs_by_size() { let chainstate_path = chainstate_path(function_name!()); let mut mempool = MemPoolDB::open_test(false, 0x80000000, &chainstate_path).unwrap(); - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut txs = vec![]; let block_height = 10; @@ -2686,10 +2632,7 @@ fn test_filter_txs_by_type() { let chainstate_path = chainstate_path(function_name!()); let mut mempool = MemPoolDB::open_test(false, 0x80000000, &chainstate_path).unwrap(); - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut txs = vec![]; let block_height = 10; let mut total_len = 0; diff --git a/stackslib/src/cost_estimates/tests/cost_estimators.rs b/stackslib/src/cost_estimates/tests/cost_estimators.rs index 1ed6b034e5..7b6e19c5d4 100644 --- a/stackslib/src/cost_estimates/tests/cost_estimators.rs +++ b/stackslib/src/cost_estimates/tests/cost_estimators.rs @@ -81,7 +81,7 @@ fn make_dummy_coinbase_tx() -> StacksTransactionReceipt { fn make_dummy_transfer_payload() -> TransactionPayload { TransactionPayload::TokenTransfer( - PrincipalData::Standard(StandardPrincipalData(0, [0; 20])), + PrincipalData::Standard(StandardPrincipalData::new(0, [0; 20]).unwrap()), 1, TokenTransferMemo([0; 34]), ) @@ -92,7 +92,7 @@ fn make_dummy_transfer_tx() -> StacksTransactionReceipt { TransactionVersion::Mainnet, TransactionAuth::Standard(TransactionSpendingCondition::new_initial_sighash()), TransactionPayload::TokenTransfer( - PrincipalData::Standard(StandardPrincipalData(0, [0; 20])), + PrincipalData::Standard(StandardPrincipalData::new(0, [0; 20]).unwrap()), 1, TokenTransferMemo([0; 34]), ), @@ -128,7 +128,7 @@ fn make_dummy_cc_tx( fn make_dummy_cc_payload(contract_name: &str, function_name: &str) -> TransactionPayload { TransactionPayload::ContractCall(TransactionContractCall { - address: StacksAddress::new(0, Hash160([0; 20])), + address: StacksAddress::new(0, Hash160([0; 20])).unwrap(), contract_name: contract_name.into(), function_name: function_name.into(), function_args: vec![], @@ -254,13 +254,13 @@ fn test_pessimistic_cost_estimator_declining_average() { fn pessimistic_estimator_contract_owner_separation() { let mut estimator = instantiate_test_db(); let cc_payload_0 = TransactionPayload::ContractCall(TransactionContractCall { - address: StacksAddress::new(0, Hash160([0; 20])), + address: StacksAddress::new(0, Hash160([0; 20])).unwrap(), contract_name: "contract-1".into(), function_name: "func1".into(), function_args: vec![], }); let cc_payload_1 = TransactionPayload::ContractCall(TransactionContractCall { - address: StacksAddress::new(0, Hash160([1; 20])), + address: StacksAddress::new(0, Hash160([1; 20])).unwrap(), contract_name: "contract-1".into(), function_name: "func1".into(), function_args: vec![], diff --git a/stackslib/src/cost_estimates/tests/fee_medians.rs b/stackslib/src/cost_estimates/tests/fee_medians.rs index 102140e86b..e89af4ca41 100644 --- a/stackslib/src/cost_estimates/tests/fee_medians.rs +++ b/stackslib/src/cost_estimates/tests/fee_medians.rs @@ -65,7 +65,7 @@ fn make_dummy_cc_tx(fee: u64, execution_cost: &ExecutionCost) -> StacksTransacti TransactionVersion::Mainnet, TransactionAuth::Standard(TransactionSpendingCondition::new_initial_sighash()), TransactionPayload::ContractCall(TransactionContractCall { - address: StacksAddress::new(0, Hash160([0; 20])), + address: StacksAddress::new(0, Hash160([0; 20])).unwrap(), contract_name: "cc-dummy".into(), function_name: "func-name".into(), function_args: vec![], diff --git a/stackslib/src/cost_estimates/tests/fee_scalar.rs b/stackslib/src/cost_estimates/tests/fee_scalar.rs index 3bfc4b966a..04c1fc27a7 100644 --- a/stackslib/src/cost_estimates/tests/fee_scalar.rs +++ b/stackslib/src/cost_estimates/tests/fee_scalar.rs @@ -83,7 +83,7 @@ fn make_dummy_transfer_tx(fee: u64) -> StacksTransactionReceipt { TransactionVersion::Mainnet, TransactionAuth::Standard(TransactionSpendingCondition::new_initial_sighash()), TransactionPayload::TokenTransfer( - PrincipalData::Standard(StandardPrincipalData(0, [0; 20])), + PrincipalData::Standard(StandardPrincipalData::new(0, [0; 20]).unwrap()), 1, TokenTransferMemo([0; 34]), ), @@ -103,7 +103,7 @@ fn make_dummy_cc_tx(fee: u64) -> StacksTransactionReceipt { TransactionVersion::Mainnet, TransactionAuth::Standard(TransactionSpendingCondition::new_initial_sighash()), TransactionPayload::ContractCall(TransactionContractCall { - address: StacksAddress::new(0, Hash160([0; 20])), + address: StacksAddress::new(0, Hash160([0; 20])).unwrap(), contract_name: "cc-dummy".into(), function_name: "func-name".into(), function_args: vec![], diff --git a/stackslib/src/net/api/tests/postblock_proposal.rs b/stackslib/src/net/api/tests/postblock_proposal.rs index 4d8551d375..af239ee078 100644 --- a/stackslib/src/net/api/tests/postblock_proposal.rs +++ b/stackslib/src/net/api/tests/postblock_proposal.rs @@ -260,10 +260,7 @@ fn test_try_make_response() { ) .unwrap(); - let stx_address = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let stx_address = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let payload = TransactionPayload::TokenTransfer( stx_address.into(), 123, diff --git a/stackslib/src/net/api/tests/postmempoolquery.rs b/stackslib/src/net/api/tests/postmempoolquery.rs index 8f921525a3..d07ca50b92 100644 --- a/stackslib/src/net/api/tests/postmempoolquery.rs +++ b/stackslib/src/net/api/tests/postmempoolquery.rs @@ -131,10 +131,7 @@ fn test_stream_mempool_txs() { let chainstate_path = chainstate_path(function_name!()); let mut mempool = MemPoolDB::open_test(false, 0x80000000, &chainstate_path).unwrap(); - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut txs = vec![]; let block_height = 10; let mut total_len = 0; @@ -351,10 +348,7 @@ fn test_stream_mempool_txs() { #[test] fn test_decode_tx_stream() { - let addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut txs = vec![]; for _i in 0..10 { let pk = StacksPrivateKey::new(); diff --git a/stackslib/src/net/codec.rs b/stackslib/src/net/codec.rs index 1f2efa15ac..1eeff85dec 100644 --- a/stackslib/src/net/codec.rs +++ b/stackslib/src/net/codec.rs @@ -774,7 +774,7 @@ fn contract_id_consensus_serialize( ) -> Result<(), codec_error> { let addr = &cid.issuer; let name = &cid.name; - write_next(fd, &addr.0)?; + write_next(fd, &addr.version())?; write_next(fd, &addr.1)?; write_next(fd, name)?; Ok(()) @@ -787,11 +787,13 @@ fn contract_id_consensus_deserialize( let bytes: [u8; 20] = read_next(fd)?; let name: ContractName = read_next(fd)?; let qn = QualifiedContractIdentifier::new( - StacksAddress { - version, - bytes: Hash160(bytes), - } - .into(), + StacksAddress::new(version, Hash160(bytes)) + .map_err(|_| { + codec_error::DeserializeError( + "Failed to make StacksAddress with given version".into(), + ) + })? + .into(), name, ); Ok(qn) diff --git a/stackslib/src/net/db.rs b/stackslib/src/net/db.rs index a770727315..8721802740 100644 --- a/stackslib/src/net/db.rs +++ b/stackslib/src/net/db.rs @@ -1924,11 +1924,11 @@ mod test { let mut stackerdbs = vec![ QualifiedContractIdentifier::new( - StandardPrincipalData(0x01, [0x02; 20]), + StandardPrincipalData::new(0x01, [0x02; 20]).unwrap(), "db-1".into(), ), QualifiedContractIdentifier::new( - StandardPrincipalData(0x02, [0x03; 20]), + StandardPrincipalData::new(0x02, [0x03; 20]).unwrap(), "db-2".into(), ), ]; @@ -2097,11 +2097,11 @@ mod test { // basic storage and retrieval let mut stackerdbs = vec![ QualifiedContractIdentifier::new( - StandardPrincipalData(0x01, [0x02; 20]), + StandardPrincipalData::new(0x01, [0x02; 20]).unwrap(), "db-1".into(), ), QualifiedContractIdentifier::new( - StandardPrincipalData(0x02, [0x03; 20]), + StandardPrincipalData::new(0x02, [0x03; 20]).unwrap(), "db-2".into(), ), ]; @@ -2127,11 +2127,11 @@ mod test { // adding DBs to the same slot just grows the total list let mut new_stackerdbs = vec![ QualifiedContractIdentifier::new( - StandardPrincipalData(0x03, [0x04; 20]), + StandardPrincipalData::new(0x03, [0x04; 20]).unwrap(), "db-3".into(), ), QualifiedContractIdentifier::new( - StandardPrincipalData(0x04, [0x05; 20]), + StandardPrincipalData::new(0x04, [0x05; 20]).unwrap(), "db-5".into(), ), ]; @@ -2332,11 +2332,11 @@ mod test { let mut stackerdbs = vec![ QualifiedContractIdentifier::new( - StandardPrincipalData(0x01, [0x02; 20]), + StandardPrincipalData::new(0x01, [0x02; 20]).unwrap(), "db-1".into(), ), QualifiedContractIdentifier::new( - StandardPrincipalData(0x02, [0x03; 20]), + StandardPrincipalData::new(0x02, [0x03; 20]).unwrap(), "db-2".into(), ), ]; @@ -2369,11 +2369,11 @@ mod test { // insert new stacker DBs -- keep one the same, and add a different one let mut changed_stackerdbs = vec![ QualifiedContractIdentifier::new( - StandardPrincipalData(0x01, [0x02; 20]), + StandardPrincipalData::new(0x01, [0x02; 20]).unwrap(), "db-1".into(), ), QualifiedContractIdentifier::new( - StandardPrincipalData(0x03, [0x04; 20]), + StandardPrincipalData::new(0x03, [0x04; 20]).unwrap(), "db-3".into(), ), ]; @@ -2409,11 +2409,11 @@ mod test { // add back stacker DBs let mut new_stackerdbs = vec![ QualifiedContractIdentifier::new( - StandardPrincipalData(0x04, [0x05; 20]), + StandardPrincipalData::new(0x04, [0x05; 20]).unwrap(), "db-4".into(), ), QualifiedContractIdentifier::new( - StandardPrincipalData(0x05, [0x06; 20]), + StandardPrincipalData::new(0x05, [0x06; 20]).unwrap(), "db-5".into(), ), ]; @@ -2437,11 +2437,11 @@ mod test { for _ in 0..2 { let mut replace_stackerdbs = vec![ QualifiedContractIdentifier::new( - StandardPrincipalData(0x06, [0x07; 20]), + StandardPrincipalData::new(0x06, [0x07; 20]).unwrap(), "db-6".into(), ), QualifiedContractIdentifier::new( - StandardPrincipalData(0x07, [0x08; 20]), + StandardPrincipalData::new(0x07, [0x08; 20]).unwrap(), "db-7".into(), ), ]; @@ -2533,11 +2533,11 @@ mod test { let mut stackerdbs = vec![ QualifiedContractIdentifier::new( - StandardPrincipalData(0x01, [0x02; 20]), + StandardPrincipalData::new(0x01, [0x02; 20]).unwrap(), "db-1".into(), ), QualifiedContractIdentifier::new( - StandardPrincipalData(0x02, [0x03; 20]), + StandardPrincipalData::new(0x02, [0x03; 20]).unwrap(), "db-2".into(), ), ]; @@ -2572,11 +2572,11 @@ mod test { // insert new stacker DBs -- keep one the same, and add a different one let mut changed_stackerdbs = vec![ QualifiedContractIdentifier::new( - StandardPrincipalData(0x01, [0x02; 20]), + StandardPrincipalData::new(0x01, [0x02; 20]).unwrap(), "db-1".into(), ), QualifiedContractIdentifier::new( - StandardPrincipalData(0x03, [0x04; 20]), + StandardPrincipalData::new(0x03, [0x04; 20]).unwrap(), "db-3".into(), ), ]; @@ -2666,11 +2666,11 @@ mod test { let mut replace_stackerdbs = vec![ QualifiedContractIdentifier::new( - StandardPrincipalData(0x06, [0x07; 20]), + StandardPrincipalData::new(0x06, [0x07; 20]).unwrap(), "db-6".into(), ), QualifiedContractIdentifier::new( - StandardPrincipalData(0x07, [0x08; 20]), + StandardPrincipalData::new(0x07, [0x08; 20]).unwrap(), "db-7".into(), ), ]; diff --git a/stackslib/src/net/stackerdb/tests/config.rs b/stackslib/src/net/stackerdb/tests/config.rs index cff4ca1059..7518af9b50 100644 --- a/stackslib/src/net/stackerdb/tests/config.rs +++ b/stackslib/src/net/stackerdb/tests/config.rs @@ -142,11 +142,11 @@ fn test_valid_and_invalid_stackerdb_configs() { Some(StackerDBConfig { chunk_size: 123, signers: vec![( - StacksAddress { - version: 26, - bytes: Hash160::from_hex("b4fdae98b64b9cd6c9436f3b965558966afe890b") - .unwrap(), - }, + StacksAddress::new( + 26, + Hash160::from_hex("b4fdae98b64b9cd6c9436f3b965558966afe890b").unwrap(), + ) + .unwrap(), 3, )], write_freq: 4, @@ -183,11 +183,11 @@ fn test_valid_and_invalid_stackerdb_configs() { Some(StackerDBConfig { chunk_size: 123, signers: vec![( - StacksAddress { - version: 26, - bytes: Hash160::from_hex("b4fdae98b64b9cd6c9436f3b965558966afe890b") - .unwrap(), - }, + StacksAddress::new( + 26, + Hash160::from_hex("b4fdae98b64b9cd6c9436f3b965558966afe890b").unwrap(), + ) + .unwrap(), 3, )], write_freq: 4, @@ -485,11 +485,11 @@ fn test_valid_and_invalid_stackerdb_configs() { Some(StackerDBConfig { chunk_size: 123, signers: vec![( - StacksAddress { - version: 26, - bytes: Hash160::from_hex("b4fdae98b64b9cd6c9436f3b965558966afe890b") - .unwrap(), - }, + StacksAddress::new( + 26, + Hash160::from_hex("b4fdae98b64b9cd6c9436f3b965558966afe890b").unwrap(), + ) + .unwrap(), 3, )], write_freq: 4, @@ -634,10 +634,11 @@ fn test_hint_replicas_override() { let expected_config = StackerDBConfig { chunk_size: 123, signers: vec![( - StacksAddress { - version: 26, - bytes: Hash160::from_hex("b4fdae98b64b9cd6c9436f3b965558966afe890b").unwrap(), - }, + StacksAddress::new( + 26, + Hash160::from_hex("b4fdae98b64b9cd6c9436f3b965558966afe890b").unwrap(), + ) + .unwrap(), 3, )], write_freq: 4, diff --git a/stackslib/src/net/stackerdb/tests/db.rs b/stackslib/src/net/stackerdb/tests/db.rs index 9bcf800529..41e2e3a324 100644 --- a/stackslib/src/net/stackerdb/tests/db.rs +++ b/stackslib/src/net/stackerdb/tests/db.rs @@ -62,67 +62,37 @@ fn test_stackerdb_create_list_delete() { let mut db = StackerDBs::connect(path, true).unwrap(); let tx = db.tx_begin(StackerDBConfig::noop()).unwrap(); - let slots = [( - StacksAddress { - version: 0x02, - bytes: Hash160([0x02; 20]), - }, - 1, - )]; + let slots = [(StacksAddress::new(0x02, Hash160([0x02; 20])).unwrap(), 1)]; // databases with one chunk tx.create_stackerdb( &QualifiedContractIdentifier::new( - StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]), - } - .into(), + StacksAddress::new(0x01, Hash160([0x01; 20])) + .unwrap() + .into(), ContractName::try_from("db1").unwrap(), ), - &[( - StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]), - }, - 1, - )], + &[(StacksAddress::new(0x01, Hash160([0x01; 20])).unwrap(), 1)], ) .unwrap(); tx.create_stackerdb( &QualifiedContractIdentifier::new( - StacksAddress { - version: 0x02, - bytes: Hash160([0x02; 20]), - } - .into(), + StacksAddress::new(0x02, Hash160([0x02; 20])) + .unwrap() + .into(), ContractName::try_from("db2").unwrap(), ), - &[( - StacksAddress { - version: 0x02, - bytes: Hash160([0x02; 20]), - }, - 1, - )], + &[(StacksAddress::new(0x02, Hash160([0x02; 20])).unwrap(), 1)], ) .unwrap(); tx.create_stackerdb( &QualifiedContractIdentifier::new( - StacksAddress { - version: 0x03, - bytes: Hash160([0x03; 20]), - } - .into(), + StacksAddress::new(0x03, Hash160([0x03; 20])) + .unwrap() + .into(), ContractName::try_from("db3").unwrap(), ), - &[( - StacksAddress { - version: 0x03, - bytes: Hash160([0x03; 20]), - }, - 1, - )], + &[(StacksAddress::new(0x03, Hash160([0x03; 20])).unwrap(), 1)], ) .unwrap(); @@ -135,27 +105,21 @@ fn test_stackerdb_create_list_delete() { dbs, vec![ QualifiedContractIdentifier::new( - StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]) - } - .into(), + StacksAddress::new(0x01, Hash160([0x01; 20])) + .unwrap() + .into(), ContractName::try_from("db1").unwrap() ), QualifiedContractIdentifier::new( - StacksAddress { - version: 0x02, - bytes: Hash160([0x02; 20]) - } - .into(), + StacksAddress::new(0x02, Hash160([0x02; 20])) + .unwrap() + .into(), ContractName::try_from("db2").unwrap() ), QualifiedContractIdentifier::new( - StacksAddress { - version: 0x03, - bytes: Hash160([0x03; 20]) - } - .into(), + StacksAddress::new(0x03, Hash160([0x03; 20])) + .unwrap() + .into(), ContractName::try_from("db3").unwrap() ), ] @@ -166,11 +130,9 @@ fn test_stackerdb_create_list_delete() { if let net_error::StackerDBExists(..) = tx .create_stackerdb( &QualifiedContractIdentifier::new( - StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]), - } - .into(), + StacksAddress::new(0x01, Hash160([0x01; 20])) + .unwrap() + .into(), ContractName::try_from("db1").unwrap(), ), &[], @@ -189,27 +151,21 @@ fn test_stackerdb_create_list_delete() { dbs, vec![ QualifiedContractIdentifier::new( - StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]) - } - .into(), + StacksAddress::new(0x01, Hash160([0x01; 20])) + .unwrap() + .into(), ContractName::try_from("db1").unwrap() ), QualifiedContractIdentifier::new( - StacksAddress { - version: 0x02, - bytes: Hash160([0x02; 20]) - } - .into(), + StacksAddress::new(0x02, Hash160([0x02; 20])) + .unwrap() + .into(), ContractName::try_from("db2").unwrap() ), QualifiedContractIdentifier::new( - StacksAddress { - version: 0x03, - bytes: Hash160([0x03; 20]) - } - .into(), + StacksAddress::new(0x03, Hash160([0x03; 20])) + .unwrap() + .into(), ContractName::try_from("db3").unwrap() ), ] @@ -223,11 +179,9 @@ fn test_stackerdb_create_list_delete() { // remove a db let tx = db.tx_begin(StackerDBConfig::noop()).unwrap(); tx.delete_stackerdb(&QualifiedContractIdentifier::new( - StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]), - } - .into(), + StacksAddress::new(0x01, Hash160([0x01; 20])) + .unwrap() + .into(), ContractName::try_from("db1").unwrap(), )) .unwrap(); @@ -240,19 +194,15 @@ fn test_stackerdb_create_list_delete() { dbs, vec![ QualifiedContractIdentifier::new( - StacksAddress { - version: 0x02, - bytes: Hash160([0x02; 20]) - } - .into(), + StacksAddress::new(0x02, Hash160([0x02; 20])) + .unwrap() + .into(), ContractName::try_from("db2").unwrap() ), QualifiedContractIdentifier::new( - StacksAddress { - version: 0x03, - bytes: Hash160([0x03; 20]) - } - .into(), + StacksAddress::new(0x03, Hash160([0x03; 20])) + .unwrap() + .into(), ContractName::try_from("db3").unwrap() ), ] @@ -266,11 +216,9 @@ fn test_stackerdb_create_list_delete() { // deletion is idempotent let tx = db.tx_begin(StackerDBConfig::noop()).unwrap(); tx.delete_stackerdb(&QualifiedContractIdentifier::new( - StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]), - } - .into(), + StacksAddress::new(0x01, Hash160([0x01; 20])) + .unwrap() + .into(), ContractName::try_from("db1").unwrap(), )) .unwrap(); @@ -283,19 +231,15 @@ fn test_stackerdb_create_list_delete() { dbs, vec![ QualifiedContractIdentifier::new( - StacksAddress { - version: 0x02, - bytes: Hash160([0x02; 20]) - } - .into(), + StacksAddress::new(0x02, Hash160([0x02; 20])) + .unwrap() + .into(), ContractName::try_from("db2").unwrap() ), QualifiedContractIdentifier::new( - StacksAddress { - version: 0x03, - bytes: Hash160([0x03; 20]) - } - .into(), + StacksAddress::new(0x03, Hash160([0x03; 20])) + .unwrap() + .into(), ContractName::try_from("db3").unwrap() ), ] @@ -313,11 +257,9 @@ fn test_stackerdb_prepare_clear_slots() { setup_test_path(path); let sc = QualifiedContractIdentifier::new( - StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]), - } - .into(), + StacksAddress::new(0x01, Hash160([0x01; 20])) + .unwrap() + .into(), ContractName::try_from("db1").unwrap(), ); @@ -327,27 +269,9 @@ fn test_stackerdb_prepare_clear_slots() { tx.create_stackerdb( &sc, &[ - ( - StacksAddress { - version: 0x02, - bytes: Hash160([0x02; 20]), - }, - 2, - ), - ( - StacksAddress { - version: 0x03, - bytes: Hash160([0x03; 20]), - }, - 3, - ), - ( - StacksAddress { - version: 0x04, - bytes: Hash160([0x04; 20]), - }, - 4, - ), + (StacksAddress::new(0x02, Hash160([0x02; 20])).unwrap(), 2), + (StacksAddress::new(0x03, Hash160([0x03; 20])).unwrap(), 3), + (StacksAddress::new(0x04, Hash160([0x04; 20])).unwrap(), 4), ], ) .unwrap(); @@ -363,28 +287,19 @@ fn test_stackerdb_prepare_clear_slots() { // belongs to 0x02 assert_eq!( slot_validation.signer, - StacksAddress { - version: 0x02, - bytes: Hash160([0x02; 20]) - } + StacksAddress::new(0x02, Hash160([0x02; 20])).unwrap() ); } else if slot_id >= 2 && slot_id < 2 + 3 { // belongs to 0x03 assert_eq!( slot_validation.signer, - StacksAddress { - version: 0x03, - bytes: Hash160([0x03; 20]) - } + StacksAddress::new(0x03, Hash160([0x03; 20])).unwrap() ); } else if slot_id >= 2 + 3 && slot_id < 2 + 3 + 4 { // belongs to 0x03 assert_eq!( slot_validation.signer, - StacksAddress { - version: 0x04, - bytes: Hash160([0x04; 20]) - } + StacksAddress::new(0x04, Hash160([0x04; 20])).unwrap() ); } else { unreachable!() @@ -424,11 +339,9 @@ fn test_stackerdb_insert_query_chunks() { setup_test_path(path); let sc = QualifiedContractIdentifier::new( - StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]), - } - .into(), + StacksAddress::new(0x01, Hash160([0x01; 20])) + .unwrap() + .into(), ContractName::try_from("db1").unwrap(), ); @@ -579,11 +492,9 @@ fn test_reconfigure_stackerdb() { setup_test_path(path); let sc = QualifiedContractIdentifier::new( - StacksAddress { - version: 0x01, - bytes: Hash160([0x01; 20]), - } - .into(), + StacksAddress::new(0x01, Hash160([0x01; 20])) + .unwrap() + .into(), ContractName::try_from("db1").unwrap(), ); diff --git a/stackslib/src/net/stackerdb/tests/sync.rs b/stackslib/src/net/stackerdb/tests/sync.rs index 627bac1abc..d4660803d2 100644 --- a/stackslib/src/net/stackerdb/tests/sync.rs +++ b/stackslib/src/net/stackerdb/tests/sync.rs @@ -69,10 +69,11 @@ impl StackerDBConfig { /// `setup_stackerdb()` fn add_stackerdb(config: &mut TestPeerConfig, stackerdb_config: Option) -> usize { let name = ContractName::try_from(format!("db-{}", config.stacker_dbs.len())).unwrap(); - let addr = StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_data(&config.stacker_dbs.len().to_be_bytes()), - }; + let addr = StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_data(&config.stacker_dbs.len().to_be_bytes()), + ) + .unwrap(); let stackerdb_config = stackerdb_config.unwrap_or(StackerDBConfig::noop()); @@ -110,10 +111,11 @@ fn setup_stackerdb(peer: &mut TestPeer, idx: usize, fill: bool, num_slots: usize } }; let pubk = StacksPublicKey::from_private(&pk); - let addr = StacksAddress { - version: C32_ADDRESS_VERSION_MAINNET_SINGLESIG, - bytes: Hash160::from_node_public_key(&pubk), - }; + let addr = StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + Hash160::from_node_public_key(&pubk), + ) + .unwrap(); pks.push(pk); slots.push((addr, 1u32)); diff --git a/stackslib/src/net/tests/convergence.rs b/stackslib/src/net/tests/convergence.rs index be35c4e1f1..c9d1fd97f3 100644 --- a/stackslib/src/net/tests/convergence.rs +++ b/stackslib/src/net/tests/convergence.rs @@ -39,7 +39,7 @@ fn setup_rlimit_nofiles() { fn stacker_db_id(i: usize) -> QualifiedContractIdentifier { QualifiedContractIdentifier::new( - StandardPrincipalData(0x01, [i as u8; 20]), + StandardPrincipalData::new(0x01, [i as u8; 20]).unwrap(), format!("db-{}", i).as_str().into(), ) } diff --git a/stackslib/src/net/tests/httpcore.rs b/stackslib/src/net/tests/httpcore.rs index 8372398533..0fd8b796ce 100644 --- a/stackslib/src/net/tests/httpcore.rs +++ b/stackslib/src/net/tests/httpcore.rs @@ -151,10 +151,7 @@ fn make_test_transaction() -> StacksTransaction { .unwrap(); let auth = TransactionAuth::from_p2pkh(&privk).unwrap(); let addr = auth.origin().address_testnet(); - let recv_addr = StacksAddress { - version: 1, - bytes: Hash160([0xff; 20]), - }; + let recv_addr = StacksAddress::new(1, Hash160([0xff; 20])).unwrap(); let mut tx_stx_transfer = StacksTransaction::new( TransactionVersion::Testnet, diff --git a/stackslib/src/net/tests/mempool/mod.rs b/stackslib/src/net/tests/mempool/mod.rs index e1430454e8..922acbcd2c 100644 --- a/stackslib/src/net/tests/mempool/mod.rs +++ b/stackslib/src/net/tests/mempool/mod.rs @@ -86,10 +86,8 @@ fn test_mempool_sync_2_peers() { peer_2.process_stacks_epoch_at_tip(&stacks_block, µblocks); } - let addr = StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_SINGLESIG, - bytes: Hash160([0xff; 20]), - }; + let addr = + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160([0xff; 20])).unwrap(); let stacks_tip_ch = peer_1.network.stacks_tip.consensus_hash.clone(); let stacks_tip_bhh = peer_1.network.stacks_tip.block_hash.clone(); @@ -354,10 +352,8 @@ fn test_mempool_sync_2_peers_paginated() { peer_2.process_stacks_epoch_at_tip(&stacks_block, µblocks); } - let addr = StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_SINGLESIG, - bytes: Hash160([0xff; 20]), - }; + let addr = + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160([0xff; 20])).unwrap(); let stacks_tip_ch = peer_1.network.stacks_tip.consensus_hash.clone(); let stacks_tip_bhh = peer_1.network.stacks_tip.block_hash.clone(); @@ -545,10 +541,8 @@ fn test_mempool_sync_2_peers_blacklisted() { peer_2.process_stacks_epoch_at_tip(&stacks_block, µblocks); } - let addr = StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_SINGLESIG, - bytes: Hash160([0xff; 20]), - }; + let addr = + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160([0xff; 20])).unwrap(); let stacks_tip_ch = peer_1.network.stacks_tip.consensus_hash.clone(); let stacks_tip_bhh = peer_1.network.stacks_tip.block_hash.clone(); @@ -756,10 +750,8 @@ fn test_mempool_sync_2_peers_problematic() { peer_2.process_stacks_epoch_at_tip(&stacks_block, µblocks); } - let addr = StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_SINGLESIG, - bytes: Hash160([0xff; 20]), - }; + let addr = + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160([0xff; 20])).unwrap(); let stacks_tip_ch = peer_1.network.stacks_tip.consensus_hash.clone(); let stacks_tip_bhh = peer_1.network.stacks_tip.block_hash.clone(); @@ -1143,10 +1135,8 @@ fn test_mempool_sync_2_peers_nakamoto_paginated() { debug!("Peers are connected"); - let addr = StacksAddress { - version: C32_ADDRESS_VERSION_TESTNET_SINGLESIG, - bytes: Hash160([0xff; 20]), - }; + let addr = + StacksAddress::new(C32_ADDRESS_VERSION_TESTNET_SINGLESIG, Hash160([0xff; 20])).unwrap(); let stacks_tip_ch = peer_1.network.stacks_tip.consensus_hash.clone(); let stacks_tip_bhh = peer_1.network.stacks_tip.block_hash.clone(); diff --git a/stackslib/src/net/tests/mod.rs b/stackslib/src/net/tests/mod.rs index ba2cb2d44a..ad5b82513d 100644 --- a/stackslib/src/net/tests/mod.rs +++ b/stackslib/src/net/tests/mod.rs @@ -443,7 +443,7 @@ impl NakamotoBootPlan { let mut other_peer_nonces = vec![0; other_peers.len()]; let addr = StacksAddress::p2pkh(false, &StacksPublicKey::from_private(&self.private_key)); let default_pox_addr = - PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, addr.bytes.clone()); + PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, addr.bytes().clone()); let mut sortition_height = peer.get_burn_block_height(); debug!("\n\n======================"); diff --git a/stackslib/src/util_lib/boot.rs b/stackslib/src/util_lib/boot.rs index 95cfca9c41..1ebf6e2af9 100644 --- a/stackslib/src/util_lib/boot.rs +++ b/stackslib/src/util_lib/boot.rs @@ -25,7 +25,7 @@ pub fn boot_code_addr(mainnet: bool) -> StacksAddress { pub fn boot_code_tx_auth(boot_code_address: StacksAddress) -> TransactionAuth { TransactionAuth::Standard(TransactionSpendingCondition::Singlesig( SinglesigSpendingCondition { - signer: boot_code_address.bytes.clone(), + signer: boot_code_address.bytes().clone(), hash_mode: SinglesigHashMode::P2PKH, key_encoding: TransactionPublicKeyEncoding::Uncompressed, nonce: 0, diff --git a/stackslib/src/util_lib/signed_structured_data.rs b/stackslib/src/util_lib/signed_structured_data.rs index 14882c2fb9..dbc279fbce 100644 --- a/stackslib/src/util_lib/signed_structured_data.rs +++ b/stackslib/src/util_lib/signed_structured_data.rs @@ -300,7 +300,9 @@ pub mod pox4 { // Test 2: invalid pox address let other_pox_address = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - StacksAddress::p2pkh(false, &Secp256k1PublicKey::new()).bytes, + StacksAddress::p2pkh(false, &Secp256k1PublicKey::new()) + .destruct() + .1, ); let result = call_get_signer_message_hash( &mut sim, diff --git a/testnet/stacks-node/src/tests/epoch_21.rs b/testnet/stacks-node/src/tests/epoch_21.rs index d50cac0117..474139f2a2 100644 --- a/testnet/stacks-node/src/tests/epoch_21.rs +++ b/testnet/stacks-node/src/tests/epoch_21.rs @@ -546,7 +546,7 @@ fn transition_fixes_bitcoin_rigidity() { let _spender_btc_addr = BitcoinAddress::from_bytes_legacy( BitcoinNetworkType::Regtest, LegacyBitcoinAddressType::PublicKeyHash, - &spender_stx_addr.bytes.0, + &spender_stx_addr.bytes().0, ) .unwrap(); diff --git a/testnet/stacks-node/src/tests/epoch_22.rs b/testnet/stacks-node/src/tests/epoch_22.rs index 493fb36fcd..2703746424 100644 --- a/testnet/stacks-node/src/tests/epoch_22.rs +++ b/testnet/stacks-node/src/tests/epoch_22.rs @@ -444,22 +444,23 @@ fn disable_pox() { let reward_cycle_max = *reward_cycle_pox_addrs.keys().max().unwrap(); let pox_addr_1 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_1).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_1).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let pox_addr_2 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_2).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_2).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let pox_addr_3 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_3).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_3).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let burn_pox_addr = PoxAddress::Standard( StacksAddress::new( 26, Hash160::from_hex("0000000000000000000000000000000000000000").unwrap(), - ), + ) + .unwrap(), Some(AddressHashMode::SerializeP2PKH), ); @@ -1110,22 +1111,23 @@ fn pox_2_unlock_all() { let reward_cycle_max = *reward_cycle_pox_addrs.keys().max().unwrap(); let pox_addr_1 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_1).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_1).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let pox_addr_2 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_2).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_2).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let pox_addr_3 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_3).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_3).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let burn_pox_addr = PoxAddress::Standard( StacksAddress::new( 26, Hash160::from_hex("0000000000000000000000000000000000000000").unwrap(), - ), + ) + .unwrap(), Some(AddressHashMode::SerializeP2PKH), ); diff --git a/testnet/stacks-node/src/tests/epoch_24.rs b/testnet/stacks-node/src/tests/epoch_24.rs index 8780d08012..c36079029c 100644 --- a/testnet/stacks-node/src/tests/epoch_24.rs +++ b/testnet/stacks-node/src/tests/epoch_24.rs @@ -540,22 +540,23 @@ fn fix_to_pox_contract() { let reward_cycle_max = *reward_cycle_pox_addrs.keys().max().unwrap(); let pox_addr_1 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_1).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_1).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let pox_addr_2 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_2).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_2).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let pox_addr_3 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_3).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_3).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let burn_pox_addr = PoxAddress::Standard( StacksAddress::new( 26, Hash160::from_hex("0000000000000000000000000000000000000000").unwrap(), - ), + ) + .unwrap(), Some(AddressHashMode::SerializeP2PKH), ); @@ -1088,7 +1089,7 @@ fn verify_auto_unlock_behavior() { info!("reward set entries: {reward_set_entries:?}"); assert_eq!( reward_set_entries[0].reward_address.bytes(), - pox_pubkey_2_stx_addr.bytes.0.to_vec() + pox_pubkey_2_stx_addr.bytes().0 ); assert_eq!( reward_set_entries[0].amount_stacked, @@ -1096,7 +1097,7 @@ fn verify_auto_unlock_behavior() { ); assert_eq!( reward_set_entries[1].reward_address.bytes(), - pox_pubkey_3_stx_addr.bytes.0.to_vec() + pox_pubkey_3_stx_addr.bytes().0 ); assert_eq!(reward_set_entries[1].amount_stacked, small_stacked as u128); } @@ -1165,7 +1166,7 @@ fn verify_auto_unlock_behavior() { assert_eq!(reward_set_entries.len(), 1); assert_eq!( reward_set_entries[0].reward_address.bytes(), - pox_pubkey_2_stx_addr.bytes.0.to_vec() + pox_pubkey_2_stx_addr.bytes().0 ); assert_eq!( reward_set_entries[0].amount_stacked, @@ -1244,22 +1245,23 @@ fn verify_auto_unlock_behavior() { let reward_cycle_max = *reward_cycle_pox_addrs.keys().max().unwrap(); let pox_addr_1 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_1).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_1).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let pox_addr_2 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_2).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_2).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let pox_addr_3 = PoxAddress::Standard( - StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_3).unwrap()), + StacksAddress::new(26, Hash160::from_hex(&pox_pubkey_hash_3).unwrap()).unwrap(), Some(AddressHashMode::SerializeP2PKH), ); let burn_pox_addr = PoxAddress::Standard( StacksAddress::new( 26, Hash160::from_hex("0000000000000000000000000000000000000000").unwrap(), - ), + ) + .unwrap(), Some(AddressHashMode::SerializeP2PKH), ); diff --git a/testnet/stacks-node/src/tests/mempool.rs b/testnet/stacks-node/src/tests/mempool.rs index 58a526ba30..e7141e8025 100644 --- a/testnet/stacks-node/src/tests/mempool.rs +++ b/testnet/stacks-node/src/tests/mempool.rs @@ -328,7 +328,7 @@ fn mempool_setup_chainstate() { // mismatched network on contract-call! let bad_addr = StacksAddress::from_public_keys( - 88, + 18, &AddressHashMode::SerializeP2PKH, 1, &vec![StacksPublicKey::from_private(&other_sk)], @@ -470,8 +470,12 @@ fn mempool_setup_chainstate() { }); // recipient must be testnet - let mut mainnet_recipient = to_addr(&other_sk); - mainnet_recipient.version = C32_ADDRESS_VERSION_MAINNET_SINGLESIG; + let testnet_recipient = to_addr(&other_sk); + let mainnet_recipient = StacksAddress::new( + C32_ADDRESS_VERSION_MAINNET_SINGLESIG, + testnet_recipient.destruct().1, + ) + .unwrap(); let mainnet_princ = mainnet_recipient.into(); let tx_bytes = make_stacks_transfer( &contract_sk, diff --git a/testnet/stacks-node/src/tests/nakamoto_integrations.rs b/testnet/stacks-node/src/tests/nakamoto_integrations.rs index 001f552f5f..13c8a93b39 100644 --- a/testnet/stacks-node/src/tests/nakamoto_integrations.rs +++ b/testnet/stacks-node/src/tests/nakamoto_integrations.rs @@ -488,10 +488,11 @@ pub fn get_latest_block_proposal( ) .map_err(|e| e.to_string())?; let miner_signed_addr = StacksAddress::p2pkh(false, &pubkey); - if miner_signed_addr.bytes != miner_addr.bytes { + if miner_signed_addr.bytes() != miner_addr.bytes() { return Err(format!( "Invalid miner signature on proposal. Found {}, expected {}", - miner_signed_addr.bytes, miner_addr.bytes + miner_signed_addr.bytes(), + miner_addr.bytes() )); } @@ -911,7 +912,7 @@ pub fn boot_to_epoch_3( for (stacker_sk, signer_sk) in stacker_sks.iter().zip(signer_sks.iter()) { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(stacker_sk).bytes, + tests::to_addr(stacker_sk).bytes().clone(), ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); @@ -1073,7 +1074,7 @@ pub fn boot_to_pre_epoch_3_boundary( for (stacker_sk, signer_sk) in stacker_sks.iter().zip(signer_sks.iter()) { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(stacker_sk).bytes, + tests::to_addr(stacker_sk).bytes().clone(), ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); @@ -1312,7 +1313,7 @@ pub fn setup_epoch_3_reward_set( for (stacker_sk, signer_sk) in stacker_sks.iter().zip(signer_sks.iter()) { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(stacker_sk).bytes, + tests::to_addr(stacker_sk).bytes().clone(), ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); @@ -2559,7 +2560,7 @@ fn correct_burn_outs() { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(account.0).bytes, + tests::to_addr(account.0).bytes().clone(), ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); @@ -11123,3 +11124,119 @@ fn test_tenure_extend_from_flashblocks() { follower_thread.join().unwrap(); } + +/// Mine a smart contract transaction with a call to `from-consensus-buff?` that would decode to an +/// invalid Principal. Verify that this transaction is dropped from the mempool. +#[test] +#[ignore] +fn mine_invalid_principal_from_consensus_buff() { + if env::var("BITCOIND_TEST") != Ok("1".into()) { + return; + } + + let (mut conf, _miner_account) = naka_neon_integration_conf(None); + let password = "12345".to_string(); + let http_origin = format!("http://{}", &conf.node.rpc_bind); + conf.connection_options.auth_token = Some(password.clone()); + conf.miner.wait_on_interim_blocks = Duration::from_secs(1); + let stacker_sk = setup_stacker(&mut conf); + let signer_sk = Secp256k1PrivateKey::new(); + let signer_addr = tests::to_addr(&signer_sk); + let sender_sk = Secp256k1PrivateKey::new(); + // setup sender + recipient for some test stx transfers + // these are necessary for the interim blocks to get mined at all + let sender_addr = tests::to_addr(&sender_sk); + conf.add_initial_balance(PrincipalData::from(sender_addr).to_string(), 1000000); + conf.add_initial_balance(PrincipalData::from(signer_addr).to_string(), 100000); + + test_observer::spawn(); + test_observer::register(&mut conf, &[EventKeyType::AnyEvent]); + + let mut btcd_controller = BitcoinCoreController::new(conf.clone()); + btcd_controller + .start_bitcoind() + .expect("Failed starting bitcoind"); + let mut btc_regtest_controller = BitcoinRegtestController::new(conf.clone(), None); + btc_regtest_controller.bootstrap_chain(201); + + let mut run_loop = boot_nakamoto::BootRunLoop::new(conf.clone()).unwrap(); + let run_loop_stopper = run_loop.get_termination_switch(); + let Counters { + blocks_processed, + naka_submitted_commits: commits_submitted, + naka_proposed_blocks: proposals_submitted, + naka_mined_blocks: mined_blocks, + .. + } = run_loop.counters(); + + let coord_channel = run_loop.coordinator_channels(); + + let run_loop_thread = thread::spawn(move || run_loop.start(None, 0)); + let mut signers = TestSigners::new(vec![signer_sk]); + wait_for_runloop(&blocks_processed); + boot_to_epoch_3( + &conf, + &blocks_processed, + &[stacker_sk], + &[signer_sk], + &mut Some(&mut signers), + &mut btc_regtest_controller, + ); + + info!("------------------------- Reached Epoch 3.0 -------------------------"); + + blind_signer(&conf, &signers, proposals_submitted); + + wait_for_first_naka_block_commit(60, &commits_submitted); + + // submit faulty contract + let contract = "(print (from-consensus-buff? principal 0x062011deadbeef11ababffff11deadbeef11ababffff0461626364))"; + + let contract_tx_bytes = make_contract_publish( + &sender_sk, + 0, + 1024, + conf.burnchain.chain_id, + "contract", + &contract, + ); + submit_tx(&http_origin, &contract_tx_bytes); + + let contract_tx = + StacksTransaction::consensus_deserialize(&mut &contract_tx_bytes[..]).unwrap(); + + // mine one more block + let blocks_before = mined_blocks.load(Ordering::SeqCst); + let blocks_processed_before = coord_channel + .lock() + .expect("Mutex poisoned") + .get_stacks_blocks_processed(); + let commits_before = commits_submitted.load(Ordering::SeqCst); + next_block_and(&mut btc_regtest_controller, 60, || { + let blocks_count = mined_blocks.load(Ordering::SeqCst); + let blocks_processed = coord_channel + .lock() + .expect("Mutex poisoned") + .get_stacks_blocks_processed(); + Ok(blocks_count > blocks_before + && blocks_processed > blocks_processed_before + && commits_submitted.load(Ordering::SeqCst) > commits_before) + }) + .unwrap(); + + let dropped_txs = test_observer::get_memtx_drops(); + + // we identified and dropped the offending tx as problematic + debug!("dropped_txs: {:?}", &dropped_txs); + assert_eq!(dropped_txs.len(), 1); + assert_eq!(dropped_txs[0].0, format!("0x{}", &contract_tx.txid())); + assert_eq!(dropped_txs[0].1.as_str(), "Problematic"); + + coord_channel + .lock() + .expect("Mutex poisoned") + .stop_chains_coordinator(); + run_loop_stopper.store(false, Ordering::SeqCst); + + run_loop_thread.join().unwrap(); +} diff --git a/testnet/stacks-node/src/tests/neon_integrations.rs b/testnet/stacks-node/src/tests/neon_integrations.rs index 9be9658f89..4c02071ddd 100644 --- a/testnet/stacks-node/src/tests/neon_integrations.rs +++ b/testnet/stacks-node/src/tests/neon_integrations.rs @@ -1909,7 +1909,7 @@ fn stx_transfer_btc_integration_test() { let _spender_btc_addr = BitcoinAddress::from_bytes_legacy( BitcoinNetworkType::Regtest, LegacyBitcoinAddressType::PublicKeyHash, - &spender_stx_addr.bytes.0, + &spender_stx_addr.bytes().0, ) .unwrap(); diff --git a/testnet/stacks-node/src/tests/signer/v0.rs b/testnet/stacks-node/src/tests/signer/v0.rs index 922bfa66c9..06c984467a 100644 --- a/testnet/stacks-node/src/tests/signer/v0.rs +++ b/testnet/stacks-node/src/tests/signer/v0.rs @@ -128,7 +128,7 @@ impl SignerTest { for stacker_sk in self.signer_stacks_private_keys.iter() { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(stacker_sk).bytes, + tests::to_addr(stacker_sk).bytes().clone(), ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); @@ -4193,7 +4193,7 @@ fn signer_set_rollover() { for stacker_sk in new_signer_private_keys.iter() { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(stacker_sk).bytes, + tests::to_addr(stacker_sk).bytes().clone(), ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); @@ -10923,7 +10923,7 @@ fn injected_signatures_are_ignored_across_boundaries() { // Stack the new signer let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(&new_signer_private_key).bytes, + tests::to_addr(&new_signer_private_key).bytes().clone(), ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); let signature = make_pox_4_signer_key_signature( From cd8f5ff9f7179f536860cb23af766860a06d0b12 Mon Sep 17 00:00:00 2001 From: Jude Nelson Date: Thu, 23 Jan 2025 13:05:32 -0500 Subject: [PATCH 16/17] chore: bump changelog version --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 141ecec71f..d9631ccf65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to the versioning scheme outlined in the [README.md](README.md). -## [Unreleased] +## [3.1.0.0.4] ### Added From 15026de2ad9fcf5ecb7d89e468344233b9534e6f Mon Sep 17 00:00:00 2001 From: Jude Nelson Date: Thu, 23 Jan 2025 13:06:43 -0500 Subject: [PATCH 17/17] chore: bump signer changelog --- stacks-signer/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stacks-signer/CHANGELOG.md b/stacks-signer/CHANGELOG.md index 5b69d090ac..2697d93508 100644 --- a/stacks-signer/CHANGELOG.md +++ b/stacks-signer/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to the versioning scheme outlined in the [README.md](README.md). -## [Unreleased] +## [3.1.0.0.4.0] ## Added