Skip to content

Commit

Permalink
Merge branch '2.0' into cleanup-wallet-syncing
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex6323 committed Mar 14, 2024
2 parents 8591c86 + d2aea56 commit 7a158a6
Show file tree
Hide file tree
Showing 53 changed files with 805 additions and 371 deletions.
6 changes: 1 addition & 5 deletions bindings/core/src/method/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ pub enum ClientMethod {
// If not provided, minimum amount will be used
#[serde(default, with = "option_string")]
amount: Option<u64>,
// TODO: Determine if `default` is wanted here
#[serde(default, with = "string")]
mana: u64,
account_id: AccountId,
Expand All @@ -58,7 +57,6 @@ pub enum ClientMethod {
// If not provided, minimum amount will be used
#[serde(default, with = "option_string")]
amount: Option<u64>,
// TODO: Determine if `default` is wanted here
#[serde(default, with = "string")]
mana: u64,
unlock_conditions: Vec<UnlockCondition>,
Expand Down Expand Up @@ -86,7 +84,6 @@ pub enum ClientMethod {
// If not provided, minimum amount will be used
#[serde(default, with = "option_string")]
amount: Option<u64>,
// TODO: Determine if `default` is wanted here
#[serde(default, with = "string")]
mana: u64,
nft_id: NftId,
Expand Down Expand Up @@ -190,10 +187,9 @@ pub enum ClientMethod {
},
/// Return the information of committee members at the given epoch index. If epoch index is not provided, the
/// current committee members are returned.
#[serde(rename_all = "camelCase")]
GetCommittee {
/// The epoch index to query.
epoch_index: Option<EpochIndex>,
epoch: Option<EpochIndex>,
},
/// Get issuance
GetIssuance,
Expand Down
2 changes: 1 addition & 1 deletion bindings/core/src/method_handler/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ pub(crate) async fn call_client_method_internal(
Response::Validators(client.get_validators(page_size, cursor).await?)
}
ClientMethod::GetValidator { account_id } => Response::Validator(client.get_validator(&account_id).await?),
ClientMethod::GetCommittee { epoch_index } => Response::Committee(client.get_committee(epoch_index).await?),
ClientMethod::GetCommittee { epoch } => Response::Committee(client.get_committee(epoch).await?),
ClientMethod::GetIssuance => Response::Issuance(client.get_issuance().await?),
ClientMethod::PostBlockRaw { block_bytes } => Response::BlockId(
client
Expand Down
6 changes: 3 additions & 3 deletions bindings/nodejs/lib/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,13 +252,13 @@ export class Client {
/**
* Returns the information of committee members at the given epoch index. If epoch index is not provided, the
* current committee members are returned.
* GET /api/core/v3/committee/?epochIndex
* GET /api/core/v3/committee/?epoch
*/
async getCommittee(epochIndex?: EpochIndex): Promise<CommitteeResponse> {
async getCommittee(epoch?: EpochIndex): Promise<CommitteeResponse> {
const response = await this.methodHandler.callMethod({
name: 'getCommittee',
data: {
epochIndex,
epoch,
},
});

Expand Down
14 changes: 8 additions & 6 deletions bindings/nodejs/lib/types/block/output/feature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

import { SlotIndex } from '../slot';
import { Type } from 'class-transformer';
import { Transform, Type } from 'class-transformer';
import { Address, AddressDiscriminator } from '../address';
import {
BlockIssuerKey,
Expand All @@ -11,7 +11,7 @@ import {
import { u256, u64 } from '../../utils/type-aliases';
import { EpochIndex } from '../../block/slot';
import { NativeToken } from '../../models/native-token';
import { HexEncodedString } from '../../utils/hex-encoding';
import { HexEncodedString, hexToBigInt } from '../../utils/hex-encoding';

/**
* Printable ASCII characters.
Expand Down Expand Up @@ -147,16 +147,18 @@ class NativeTokenFeature extends Feature {
/**
* Amount of native tokens of the given Token ID.
*/
@Transform((value) => hexToBigInt(value.value))
readonly amount: u256;

/**
* Creates a new `NativeTokenFeature`.
* @param nativeToken The native token stored with the feature.
* @param id The identifier of the native token.
* @param amount The native token amount.
*/
constructor(nativeToken: NativeToken) {
constructor(id: HexEncodedString, amount: u256) {
super(FeatureType.NativeToken);
this.id = nativeToken.id;
this.amount = nativeToken.amount;
this.id = id;
this.amount = amount;
}

/**
Expand Down
1 change: 1 addition & 0 deletions bindings/nodejs/lib/types/block/output/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ class BasicOutput extends CommonOutput {

/**
* @param amount The amount of the output.
* @param mana The mana of the output.
* @param unlockConditions The unlock conditions for the output.
*/
constructor(amount: u64, mana: u64, unlockConditions: UnlockCondition[]) {
Expand Down
2 changes: 1 addition & 1 deletion bindings/nodejs/lib/types/client/bridge/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export interface __GetValidatorMethod__ {
export interface __GetCommitteeMethod__ {
name: 'getCommittee';
data: {
epochIndex?: EpochIndex;
epoch?: EpochIndex;
};
}

Expand Down
2 changes: 0 additions & 2 deletions bindings/nodejs/lib/types/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ export type ClientErrorName =
| 'inputAddressNotFound'
| 'invalidAmount'
| 'invalidMnemonic'
| 'invalidTransactionLength'
| 'invalidSignedTransactionPayloadLength'
| 'json'
| 'missingParameter'
| 'node'
Expand Down
6 changes: 3 additions & 3 deletions bindings/python/iota_sdk/client/_node_core_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,13 +144,13 @@ def get_validator(self, account_id: HexStr) -> ValidatorResponse:
# Committee routes.

def get_committee(
self, epoch_index: Optional[EpochIndex] = None) -> CommitteeResponse:
self, epoch: Optional[EpochIndex] = None) -> CommitteeResponse:
"""Returns the information of committee members at the given epoch index. If epoch index is not provided, the
current committee members are returned.
GET /api/core/v3/committee/?epochIndex
GET /api/core/v3/committee/?epoch
"""
return CommitteeResponse.from_dict(self._call_method('getCommittee', {
'epochIndex': epoch_index
'epoch': epoch
}))

# Block routes.
Expand Down
12 changes: 10 additions & 2 deletions bindings/python/iota_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,15 @@ def compute_account_id(output_id: OutputId) -> HexStr:
"""Compute the account id for the given account output id.
"""
return _call_method('blake2b256Hash', {
'bytes': repr(output_id)
'bytes': output_id
})

@staticmethod
def compute_delegation_id(output_id: OutputId) -> HexStr:
"""Compute the delegation id for the given account output id.
"""
return _call_method('blake2b256Hash', {
'bytes': output_id
})

@staticmethod
Expand Down Expand Up @@ -113,7 +121,7 @@ def compute_nft_id(output_id: OutputId) -> HexStr:
"""Compute the NFT id for the given NFT output id.
"""
return _call_method('blake2b256Hash', {
'bytes': repr(output_id)
'bytes': output_id
})

@staticmethod
Expand Down
11 changes: 11 additions & 0 deletions bindings/python/tests/test_offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,14 @@ def test_irc_30():
}
metadata_deser = Irc30Metadata.from_dict(metadata_dict)
assert metadata == metadata_deser


def test_output_id_hashing():
output_id = OutputId(
'0x0000000000000000000000000000000000000000000000000000000000000000000000000000')
assert Utils.compute_account_id(
output_id) == '0x0ebc2867a240719a70faacdfc3840e857fa450b37d95297ac4f166c2f70c3345'
assert Utils.compute_delegation_id(
output_id) == '0x0ebc2867a240719a70faacdfc3840e857fa450b37d95297ac4f166c2f70c3345'
assert Utils.compute_nft_id(
output_id) == '0x0ebc2867a240719a70faacdfc3840e857fa450b37d95297ac4f166c2f70c3345'
39 changes: 32 additions & 7 deletions sdk/examples/client/block/02_block_custom_parents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ use iota_sdk::{
secret::{SecretManager, SignBlock},
Client,
},
types::block::output::AccountId,
types::block::{
core::{basic::MaxBurnedManaAmount, BasicBlockBodyBuilder, BlockHeader},
output::AccountId,
UnsignedBlock,
},
};

#[tokio::main]
Expand All @@ -39,16 +43,37 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let issuance = client.get_issuance().await?;
println!("Issuance:\n{issuance:#?}");

let protocol_params = client.get_protocol_parameters().await?;

// Create and send the block with custom parents.
// TODO build block with custom parents, but without `build_basic_block()`
let block = client
.build_basic_block(issuer_id, None)
.await?
.sign_ed25519(&secret_manager, Bip44::new(IOTA_COIN_TYPE))
.await?;
let block = UnsignedBlock::new(
BlockHeader::new(
protocol_params.version(),
protocol_params.network_id(),
time::OffsetDateTime::now_utc().unix_timestamp_nanos() as _,
issuance.latest_commitment.id(),
issuance.latest_finalized_slot,
issuer_id,
),
BasicBlockBodyBuilder::new(
issuance.strong_parents()?,
MaxBurnedManaAmount::MinimumAmount {
params: protocol_params.work_score_parameters(),
reference_mana_cost: client
.get_account_congestion(&issuer_id, None)
.await?
.reference_mana_cost,
},
)
.finish_block_body()?,
)
.sign_ed25519(&secret_manager, Bip44::new(IOTA_COIN_TYPE))
.await?;

println!("{block:#?}");

client.post_block(&block).await?;

println!(
"Block with custom parents sent: {}/block/{}",
std::env::var("EXPLORER_URL").unwrap(),
Expand Down
2 changes: 0 additions & 2 deletions sdk/examples/wallet/offline_signing/2_sign_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

let signed_transaction = SignedTransactionPayload::new(prepared_transaction_data.transaction.clone(), unlocks)?;

signed_transaction.validate_length()?;

let signed_transaction_data = SignedTransactionData {
payload: signed_transaction,
inputs_data: prepared_transaction_data.inputs_data,
Expand Down
9 changes: 2 additions & 7 deletions sdk/src/client/api/block_builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,10 @@ impl Client {
let issuance = self.get_issuance().await?;

let issuing_time = {
#[cfg(feature = "std")]
let issuing_time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
let issuing_time = instant::SystemTime::now()
.duration_since(instant::SystemTime::UNIX_EPOCH)
.expect("Time went backwards")
.as_nanos() as u64;
// TODO no_std way to have a nanosecond timestamp
// https://github.com/iotaledger/iota-sdk/issues/647
#[cfg(not(feature = "std"))]
let issuing_time = 0;

// Check that the issuing_time is in the range of +-5 minutes of the node to prevent potential issues
if !(issuance.latest_parent_block_issuing_time - FIVE_MINUTES_IN_NANOSECONDS
Expand Down
59 changes: 1 addition & 58 deletions sdk/src/client/api/block_builder/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,15 @@

//! Transaction preparation and signing

use packable::PackableExt;

use crate::{
client::{
api::{PreparedTransactionData, SignedTransactionData},
ClientError,
},
client::api::{PreparedTransactionData, SignedTransactionData},
types::block::{
output::{Output, OutputId},
payload::signed_transaction::{SignedTransactionPayload, Transaction},
protocol::ProtocolParameters,
semantic::{SemanticValidationContext, TransactionFailureReason},
signature::Ed25519Signature,
Block, BlockId,
},
};

// TODO this is wrong because of https://github.com/iotaledger/iota-sdk/issues/1208
const MAX_TX_LENGTH_FOR_BLOCK_WITH_8_PARENTS: usize = Block::LENGTH_MAX - Block::LENGTH_MIN - (7 * BlockId::LENGTH);
// Length for unlocks with a single signature unlock (unlocks length + unlock type + signature type + public key +
// signature)
const SINGLE_UNLOCK_LENGTH: usize = 1 + 1 + Ed25519Signature::PUBLIC_KEY_LENGTH + Ed25519Signature::SIGNATURE_LENGTH;
// Type + reference index
const REFERENCE_ACCOUNT_NFT_UNLOCK_LENGTH: usize = 1 + 2;

impl PreparedTransactionData {
/// Verifies the semantic of a prepared transaction.
pub fn verify_semantic(&self, protocol_parameters: &ProtocolParameters) -> Result<(), TransactionFailureReason> {
Expand Down Expand Up @@ -69,44 +53,3 @@ impl SignedTransactionData {
context.validate()
}
}

impl SignedTransactionPayload {
/// Verifies that the signed transaction payload doesn't exceed the block size limit with 8 parents.
pub fn validate_length(&self) -> Result<(), ClientError> {
let signed_transaction_payload_bytes = self.pack_to_vec();
if signed_transaction_payload_bytes.len() > MAX_TX_LENGTH_FOR_BLOCK_WITH_8_PARENTS {
return Err(ClientError::InvalidSignedTransactionPayloadLength {
length: signed_transaction_payload_bytes.len(),
max_length: MAX_TX_LENGTH_FOR_BLOCK_WITH_8_PARENTS,
});
}
Ok(())
}
}

impl Transaction {
/// Verifies that the transaction doesn't exceed the block size limit with 8 parents.
/// Assuming one signature unlock and otherwise reference/account/nft unlocks.
/// `validate_transaction_payload_length()` should later be used to check the length again with the correct
/// unlocks.
pub fn validate_length(&self) -> Result<(), ClientError> {
let transaction_bytes = self.pack_to_vec();

// Assuming there is only 1 signature unlock and the rest is reference/account/nft unlocks
let reference_account_nft_unlocks_amount = self.inputs().len() - 1;

// Max tx payload length - length for one signature unlock (there might be more unlocks, we check with them
// later again, when we built the transaction payload)
let max_length = MAX_TX_LENGTH_FOR_BLOCK_WITH_8_PARENTS
- SINGLE_UNLOCK_LENGTH
- (reference_account_nft_unlocks_amount * REFERENCE_ACCOUNT_NFT_UNLOCK_LENGTH);

if transaction_bytes.len() > max_length {
return Err(ClientError::InvalidTransactionLength {
length: transaction_bytes.len(),
max_length,
});
}
Ok(())
}
}
Loading

0 comments on commit 7a158a6

Please sign in to comment.