Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't clone env on each call of Expr::eval #740

Merged
merged 5 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ jobs:
name: Code coverage in tests
runs-on: ubuntu-latest
container:
image: xd009642/tarpaulin:latest
options: --security-opt seccomp=unconfined
image: xd009642/tarpaulin:latest
options: --security-opt seccomp=unconfined
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Generate code coverage
- name: Checkout repository
uses: actions/checkout@v2
- name: Generate code coverage
run: |
cargo tarpaulin --avoid-cfg-tarpaulin --timeout=360 --out lcov --exclude-files 'bindings/**/*.*' --exclude-files 'ergo-rest/src/reqwest.rs' --exclude-files 'ergo-rest/src/reqwest/**/*.*' --exclude-files 'ergo-rest/src/wasm_timer.rs' --exclude-files 'ergo-rest/src/wasm_timer/**/*.*'
- name: Push code coverage results to coveralls.io
Expand Down Expand Up @@ -164,15 +164,15 @@ jobs:
with:
token: ${{ secrets.NPM_TOKEN }}
package: ./bindings/ergo-lib-wasm/pkg-nodejs/package.json
tag: 'alpha'
tag: "alpha"

- name: publish browser alpha version to npm
if: env.HAS_NPM_TOKEN == 'true'
uses: JS-DevTools/npm-publish@v1
with:
token: ${{ secrets.NPM_TOKEN }}
package: ./bindings/ergo-lib-wasm/pkg-browser/package.json
tag: 'alpha'
tag: "alpha"

rustfmt:
name: Code formatting (rustfmt)
Expand Down Expand Up @@ -230,7 +230,7 @@ jobs:

- uses: actions-rs/toolchain@v1
with:
toolchain: nightly-2023-05-17
toolchain: nightly-2024-01-26
override: true

- name: install deps
Expand All @@ -253,7 +253,7 @@ jobs:

android_tests:
name: Test JNI(Android) bindings
runs-on: macos-latest
runs-on: macos-12
steps:
- name: checkout
uses: actions/checkout@v2
Expand All @@ -273,6 +273,6 @@ jobs:
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 29
ndk: 21.3.6528147
ndk: 26.2.11394342
emulator-build: 6110076
script: cd ./bindings/ergo-lib-jni && ./gradlew connectedCheck
16 changes: 4 additions & 12 deletions bindings/ergo-lib-c-core/src/json.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
//! JSON serialization according to EIP-12 (using strings for BoxValue and TokenAmount)

use std::convert::TryInto;

use derive_more::FromStr;
use ergo_lib::chain::transaction::unsigned::UnsignedTransaction;
use ergo_lib::chain::transaction::DataInput;
Expand Down Expand Up @@ -39,11 +37,8 @@ impl From<Transaction> for TransactionJsonEip12 {
fn from(t: Transaction) -> Self {
TransactionJsonEip12 {
tx_id: t.id(),
inputs: t.inputs.try_into().unwrap(),
data_inputs: t
.data_inputs
.map(|di| di.try_into().unwrap())
.unwrap_or_else(Vec::new),
inputs: t.inputs.into(),
data_inputs: t.data_inputs.map(|di| di.into()).unwrap_or_default(),
outputs: t.outputs.into_iter().map(|b| b.into()).collect(),
}
}
Expand All @@ -67,11 +62,8 @@ pub(crate) struct UnsignedTransactionJsonEip12 {
impl From<UnsignedTransaction> for UnsignedTransactionJsonEip12 {
fn from(t: UnsignedTransaction) -> Self {
UnsignedTransactionJsonEip12 {
inputs: t.inputs.try_into().unwrap(),
data_inputs: t
.data_inputs
.map(|di| di.try_into().unwrap())
.unwrap_or_else(Vec::new),
inputs: t.inputs.into(),
data_inputs: t.data_inputs.map(|di| di.into()).unwrap_or_default(),
outputs: t.output_candidates.into_iter().map(|b| b.into()).collect(),
}
}
Expand Down
2 changes: 1 addition & 1 deletion bindings/ergo-lib-jni/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ android {

useLibrary 'android.test.runner'

ndkVersion "21.3.6528147"
ndkVersion "26.2.11394342"

defaultConfig {
minSdkVersion buildConfig.minSdkVersion
Expand Down
11 changes: 3 additions & 8 deletions bindings/ergo-lib-wasm/src/json.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
//! JSON serialization according to EIP-12 (using strings for BoxValue and TokenAmount)

use std::convert::TryInto;

use derive_more::FromStr;
use ergo_lib::chain::transaction::unsigned::UnsignedTransaction;
use ergo_lib::chain::transaction::DataInput;
Expand Down Expand Up @@ -43,7 +41,7 @@ impl From<Transaction> for TransactionJsonEip12 {
data_inputs: t
.data_inputs
.map(|di| di.as_vec().clone())
.unwrap_or_else(Vec::new),
.unwrap_or_default(),
outputs: t.outputs.into_iter().map(|b| b.into()).collect(),
}
}
Expand All @@ -69,11 +67,8 @@ impl From<UnsignedTransaction> for UnsignedTransactionJsonEip12 {
// Following unwraps are fine since we're converting from BoundedVec to Vec.
#[allow(clippy::unwrap_used)]
UnsignedTransactionJsonEip12 {
inputs: t.inputs.try_into().unwrap(),
data_inputs: t
.data_inputs
.map(|di| di.try_into().unwrap())
.unwrap_or_else(Vec::new),
inputs: t.inputs.into(),
data_inputs: t.data_inputs.map(|di| di.into()).unwrap_or_default(),
outputs: t.output_candidates.into_iter().map(|b| b.into()).collect(),
}
}
Expand Down
4 changes: 1 addition & 3 deletions bindings/ergo-lib-wasm/src/verifier.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
//! Verifier

use std::convert::TryFrom;

use ergo_lib::ergotree_ir::sigma_protocol::sigma_boolean::SigmaBoolean;
use wasm_bindgen::{prelude::*, JsValue};

Expand All @@ -15,7 +13,7 @@ pub fn verify_signature(
signature: &[u8],
) -> Result<bool, JsValue> {
if let Address(ergo_lib::ergotree_ir::chain::address::Address::P2Pk(d)) = address.clone() {
let sb = SigmaBoolean::try_from(d).map_err(|e| JsValue::from_str(&format!("{:?}", e)))?;
let sb = SigmaBoolean::from(d);
ergo_lib::ergotree_interpreter::sigma_protocol::verifier::verify_signature(
sb, message, signature,
)
Expand Down
6 changes: 3 additions & 3 deletions bindings/ergo-lib-wasm/tests_browser/test_rest_api.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ it('node REST API: peer_discovery endpoint', async () => {
// there's an unavoidable waiting time of 80 seconds, to give Chrome time to relinquish failed
// preflight requests)
let is_chrome = true;
let active_peers = await ergo_wasm.peer_discovery(seeds, 150, 140, is_chrome);
let active_peers = await ergo_wasm.peer_discovery(seeds, 20, 200, is_chrome);
assert(active_peers.len() > 0);
console.log("Number active peers:", active_peers.len(), ". First active peer: ", active_peers.get(0).href);
});
Expand All @@ -25,10 +25,10 @@ it('node REST API: peer_discovery endpoint (INCREMENTAL VERSION)', async () => {
const seeds = get_ergo_node_seeds();
let scan = new ergo_wasm.ChromePeerDiscoveryScan(seeds);

scan = await ergo_wasm.incremental_peer_discovery_chrome(scan, 150, 90);
scan = await ergo_wasm.incremental_peer_discovery_chrome(scan, 20, 200);
let scan_1_len = scan.active_peers().len();
console.log("# active peers from first scan:", scan_1_len);
scan = await ergo_wasm.incremental_peer_discovery_chrome(scan, 150, 480);
scan = await ergo_wasm.incremental_peer_discovery_chrome(scan, 20, 480);
let scan_2_len = scan.active_peers().len();
console.log("# active peers from second scan:", scan_2_len);

Expand Down
2 changes: 1 addition & 1 deletion ergo-lib/src/chain/ergo_box/box_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ mod tests {
let token_name = "USD".to_string();
let token_desc = "Nothing backed USD token".to_string();
let token_num_dec = 2;
vec![R4, R5, R6].iter().for_each(|r_id| {
[R4, R5, R6].iter().for_each(|r_id| {
let mut box_builder =
ErgoBoxCandidateBuilder::new(out_box_value, force_any_val::<ErgoTree>(), 0);
box_builder.mint_token(
Expand Down
6 changes: 3 additions & 3 deletions ergo-lib/src/wallet/box_selector/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ mod tests {
fn test_select_change_value_is_too_small(inputs in
vec(any_with::<ErgoBoxAssetsData>(
(BoxValue::MIN_RAW * 1000 .. BoxValue::MIN_RAW * 10000).into()), 2..10)) {
let first_input_box = inputs.get(0).unwrap().clone();
let first_input_box = inputs.first().unwrap().clone();
let s = SimpleBoxSelector::new();
let target_balance = BoxValue::try_from(first_input_box.value().as_u64() - 1).unwrap();
let selection = s.select(inputs, target_balance, vec![].as_slice()).unwrap();
Expand All @@ -376,7 +376,7 @@ mod tests {
(BoxValue::MIN_RAW * 1000 .. BoxValue::MIN_RAW * 10000).into()), 2..10),
target_balance in
any_with::<BoxValue>((BoxValue::MIN_RAW * 100 .. BoxValue::MIN_RAW * 1500).into())) {
let first_input_box = inputs.get(0).unwrap().clone();
let first_input_box = inputs.first().unwrap().clone();
prop_assume!(first_input_box.tokens.is_some());
let first_input_box_token = first_input_box.tokens.as_ref().unwrap().first();
let first_input_box_token_amount = u64::from(first_input_box_token.amount);
Expand Down Expand Up @@ -535,7 +535,7 @@ mod tests {
let s = SimpleBoxSelector::new();
let all_input_tokens = sum_tokens_from_boxes(inputs.as_slice()).unwrap();
prop_assume!(!all_input_tokens.is_empty());
let target_token_id = all_input_tokens.keys().collect::<Vec<&TokenId>>().get(0).cloned().unwrap();
let target_token_id = all_input_tokens.keys().collect::<Vec<&TokenId>>().first().cloned().unwrap();
let input_token_amount = u64::from(*all_input_tokens.get(target_token_id).unwrap()) / 2;
let target_token_amount = TokenAmount::MAX_RAW;
prop_assume!(input_token_amount < target_token_amount);
Expand Down
2 changes: 1 addition & 1 deletion ergo-lib/src/wallet/signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ mod tests {
// boxes_to_spend are in the different order to test inputs <-> boxes_to_spend association in the
// prover (it should not depend on both of them to be in the same order)
boxes_to_spend.shuffle(&mut thread_rng());
let ergo_tree = ErgoTree::try_from(Expr::Const(secrets.get(0).unwrap().public_image().into())).unwrap();
let ergo_tree = ErgoTree::try_from(Expr::Const(secrets.first().unwrap().public_image().into())).unwrap();
let candidate = ErgoBoxCandidateBuilder::new(BoxValue::SAFE_USER_MIN, ergo_tree, 0)
.build().unwrap();
let output_candidates = vec![candidate];
Expand Down
2 changes: 1 addition & 1 deletion ergo-merkle-tree/src/batchmerkleproof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl BatchMerkleProof {
let e: Vec<BatchMerkleProofIndex> = a_new
.iter()
.copied()
.zip(e_new.into_iter())
.zip(e_new)
.map(|(index, hash)| BatchMerkleProofIndex { index, hash })
.collect();
e_new = validate(&a_new, &e, &m_new)?;
Expand Down
4 changes: 2 additions & 2 deletions ergo-merkle-tree/src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl From<LevelNode> for LevelNodeJson {
Self(
node.hash
.map(|hash| base16::encode_lower(&hash))
.unwrap_or_else(String::new),
.unwrap_or_default(),
node.side,
)
}
Expand Down Expand Up @@ -136,7 +136,7 @@ impl From<LevelNode> for BatchLevelNodeJson {
digest: node
.hash
.map(|hash| base16::encode_lower(&hash))
.unwrap_or_else(String::new),
.unwrap_or_default(),
side: node.side,
}
}
Expand Down
4 changes: 2 additions & 2 deletions ergo-merkle-tree/src/merkletree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ impl MerkleTree {
/// Returns the root hash for MerkleTree. If the tree is empty, then returns [0; 32]
pub fn root_hash(&self) -> Digest32 {
self.nodes
.get(0)
.first()
.and_then(MerkleNode::get_hash)
.cloned()
.unwrap_or_else(Digest32::zero)
Expand All @@ -219,7 +219,7 @@ impl MerkleTree {
/// See: <https://github.com/ergoplatform/ergo/issues/1077>
pub fn root_hash_special(&self) -> Digest32 {
self.nodes
.get(0)
.first()
.and_then(MerkleNode::get_hash)
.cloned()
.unwrap_or_else(|| {
Expand Down
2 changes: 1 addition & 1 deletion ergo-nipopow/src/nipopow_proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ impl PoPowHeader {
.map(|(k, v)| -> Vec<u8> {
std::iter::once(2u8)
.chain(k.iter().copied())
.chain(v.into_iter())
.chain(v)
.collect()
})
.map(ergo_merkle_tree::MerkleNode::from_bytes)
Expand Down
31 changes: 16 additions & 15 deletions ergo-rest/src/api/peer_discovery_internals/chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,13 @@ pub(crate) async fn peer_discovery_inner_chrome(
max_parallel_tasks: BoundedU16<1, { u16::MAX }>,
timeout: Duration,
) -> Result<ChromePeerDiscoveryScan, PeerDiscoveryError> {
if timeout.as_secs() < 90 {
if timeout.as_secs() < 180 {
return Err(PeerDiscoveryError::TimeoutTooShort);
}

// Note that 80 seconds is allocated to waiting for preflight requests to naturally timeout by
// Chrome. The remaining time is spent looking for peers.
let global_timeout = timeout.checked_sub(Duration::from_secs(80)).unwrap();
let global_timeout = timeout.checked_sub(Duration::from_secs(180)).unwrap();
let settings = PeerDiscoverySettings {
max_parallel_tasks,
task_2_buffer_length: 50,
Expand Down Expand Up @@ -340,10 +340,11 @@ async fn peer_discovery_impl_chrome(
while let Some(req) = pending_requests.pop() {
pending_requests_after_timeout.push(req);
}
//console_log!(
// "GLOBAL TIMEOUT, {} incomplete requests-------------------------",
// pending_requests_after_timeout.len()
//);
// console_log!(
// "GLOBAL TIMEOUT, {} incomplete requests-------------------------",
// pending_requests_after_timeout.len()
// );
break;
}
}
}
Expand All @@ -355,15 +356,15 @@ async fn peer_discovery_impl_chrome(
.cloned()
.collect();
// Uncomment for debugging
//console_log!("Active_peers: {:?}", active_peers);
//console_log!(
// "Total # nodes visited: {}, # peers found: {}, # incomplete requests: {}",
// visited_peers.len(),
// active_peers.len(),
// pending_requests_after_timeout.len(),
//);
//console_log!("Waiting 80sec for Chrome to relinquish pending HTTP requests");
crate::wasm_timer::Delay::new(Duration::from_secs(80)).await?;
// console_log!("Active_peers: {:?}", active_peers);
// console_log!(
// "Total # nodes visited: {}, # peers found: {}, # incomplete requests: {}",
// visited_peers.len(),
// active_peers.len(),
// pending_requests_after_timeout.len(),
// );
//console_log!("Waiting 180sec for Chrome to relinquish pending HTTP requests");
crate::wasm_timer::Delay::new(Duration::from_secs(180)).await?;
Ok(ChromePeerDiscoveryScan {
active_peers,
visited_peers,
Expand Down
5 changes: 2 additions & 3 deletions ergo-rest/src/api/peer_discovery_internals/non_chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ use url::Url;
//
//#[cfg(target_arch = "wasm32")]
//macro_rules! console_log {
//// Note that this is using the `log` function imported above during
//// `bare_bones`
/// Note that this is using the `log` function imported above during
/// `bare_bones`
//($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
//}

Expand Down Expand Up @@ -237,7 +237,6 @@ async fn peer_discovery_impl<
drop(tx_url);
let coll: Vec<_> = visited_active_peers
.difference(&seeds_set)
.into_iter()
.cloned()
.collect();

Expand Down
4 changes: 2 additions & 2 deletions ergo-rest/src/wasm_timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
pub use timer::*;

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub use std::time::{Instant, SystemTime, UNIX_EPOCH};
pub(crate) use std::time::Instant;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
pub use wasm::*;
use wasm::*;

mod timer;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
Expand Down
4 changes: 1 addition & 3 deletions ergo-rest/src/wasm_timer/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,6 @@ mod global;
mod heap;

pub mod ext;
pub use ext::{TryFutureExt, TryStreamExt};

/// A "timer heap" used to power separately owned instances of `Delay` and
/// `Interval`.
Expand Down Expand Up @@ -287,7 +286,6 @@ pub struct TimerHandle {
mod delay;
mod interval;
pub use self::delay::Delay;
pub use self::interval::Interval;

struct Inner {
/// List of updates the `Timer` needs to process
Expand Down Expand Up @@ -583,7 +581,7 @@ impl Default for TimerHandle {
unsafe {
let handle = TimerHandle::from_usize(fallback);
let ret = handle.clone();
drop(handle.into_usize());
handle.into_usize();
return ret;
}
}
Expand Down
3 changes: 1 addition & 2 deletions ergo-rest/src/wasm_timer/timer/global/desktop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ fn run(timer: Timer, done: Arc<AtomicBool>) {

pin_mut!(timer);
while !done.load(Ordering::SeqCst) {
drop(timer.as_mut().poll(&mut cx));

let _ = timer.as_mut().poll(&mut cx);
timer.advance();
match timer.next_event() {
// Ok, block for the specified time
Expand Down
Loading
Loading