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

Add block work score method to bindings utils #2208

Merged
merged 2 commits into from
Mar 28, 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
11 changes: 10 additions & 1 deletion bindings/core/src/method/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use iota_sdk::{
dto::{SignedTransactionPayloadDto, TransactionDto},
TransactionId,
},
protocol::ProtocolParameters,
protocol::{ProtocolParameters, WorkScoreParameters},
signature::Ed25519Signature,
slot::{SlotCommitment, SlotIndex},
unlock::Unlock,
Expand Down Expand Up @@ -187,4 +187,13 @@ pub enum UtilsMethod {
},
IotaMainnetProtocolParameters,
ShimmerMainnetProtocolParameters,
/// Returns the work score of a block.
/// Expected response: [`WorkScore`](crate::Response::WorkScore)
#[serde(rename_all = "camelCase")]
BlockWorkScore {
/// Block
block: BlockDto,
/// Work score parameters
work_score_parameters: WorkScoreParameters,
},
}
15 changes: 14 additions & 1 deletion bindings/core/src/method_handler/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ use iota_sdk::{
input::UtxoInput,
output::{FoundryId, MinimumOutputAmount, Output, OutputId, TokenId},
payload::{signed_transaction::Transaction, SignedTransactionPayload},
protocol::WorkScore,
semantic::SemanticValidationContext,
signature::SignatureError,
Block,
Block, BlockBody,
},
TryFromDto,
},
Expand Down Expand Up @@ -169,6 +170,18 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
UtilsMethod::ShimmerMainnetProtocolParameters => Response::ProtocolParameters(
iota_sdk::types::block::protocol::shimmer_mainnet_protocol_parameters().clone(),
),
UtilsMethod::BlockWorkScore {
block,
work_score_parameters,
} => {
let block = Block::try_from_dto(block)?;
let work_score = match block.body() {
BlockBody::Basic(basic) => basic.work_score(work_score_parameters),
// Validation blocks have a work score of 0.
BlockBody::Validation(_validation) => 0,
};
Response::WorkScore(work_score)
}
};

Ok(response)
Expand Down
2 changes: 2 additions & 0 deletions bindings/core/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,8 @@ pub enum Response {
CustomJson(serde_json::Value),
/// Response for [`ComputeSlotCommitmentId`](crate::method::UtilsMethod::ComputeSlotCommitmentId)
SlotCommitmentId(SlotCommitmentId),
/// Response for [`BlockWorkScore`](crate::method::UtilsMethod::BlockWorkScore)
WorkScore(u32),

// Responses in client and wallet
/// Response for:
Expand Down
4 changes: 4 additions & 0 deletions bindings/nodejs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## 2.0.0-alpha.2 - 2024-MM-DD

### Added

- `Utils::blockWorkScore()`;

### Fixed

- `RestrictedAddress` discriminator usage;
Expand Down
4 changes: 3 additions & 1 deletion bindings/nodejs/lib/types/utils/bridge/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import type {
__BlockBytes__,
__IotaMainnetProtocolParameters__,
__ShimmerMainnetProtocolParameters__,
__BlockWorkScore__,
} from './utils';

export type __UtilsMethods__ =
Expand Down Expand Up @@ -59,4 +60,5 @@ export type __UtilsMethods__ =
| __VerifyTransactionSyntax__
| __BlockBytes__
| __IotaMainnetProtocolParameters__
| __ShimmerMainnetProtocolParameters__;
| __ShimmerMainnetProtocolParameters__
| __BlockWorkScore__;
9 changes: 9 additions & 0 deletions bindings/nodejs/lib/types/utils/bridge/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import { AccountId } from '../../block/id';
import { SlotCommitment } from '../../block/slot';
import { InputSigningData } from '../../client';
import { WorkScoreParameters } from '../../models';
import { NumericString } from '../numeric';

export interface __GenerateMnemonicMethod__ {
Expand Down Expand Up @@ -242,3 +243,11 @@ export interface __IotaMainnetProtocolParameters__ {
export interface __ShimmerMainnetProtocolParameters__ {
name: 'shimmerMainnetProtocolParameters';
}

export interface __BlockWorkScore__ {
name: 'blockWorkScore';
data: {
block: Block;
workScoreParameters: WorkScoreParameters;
};
}
21 changes: 21 additions & 0 deletions bindings/nodejs/lib/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
DecayedMana,
NumericString,
Ed25519Address,
WorkScoreParameters,
} from '../types';
import {
AccountId,
Expand Down Expand Up @@ -638,4 +639,24 @@ export class Utils {
});
return params;
}

/**
* Returns the work score of a block.
*
* @param block The block.
* @param workScoreParameters The WorkScoreParameters.
* @returns The work score of the block.
*/
static blockWorkScore(
block: Block,
workScoreParameters: WorkScoreParameters,
): number {
return callUtilsMethod({
name: 'blockWorkScore',
data: {
block,
workScoreParameters,
},
});
}
}
16 changes: 15 additions & 1 deletion bindings/nodejs/tests/utils/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ import 'dotenv/config';
import { BasicOutput, BlockId, OutputId, TransactionId, Utils } from '../../out';
import '../customMatchers';
import { SlotCommitment } from '../../out/types/block/slot';
import * as protocol_parameters from '../../../../sdk/tests/types/fixtures/protocol_parameters.json';
import { ProtocolParameters } from '../../lib/types/models/api';
import * as protocol_parameters from '../../../../sdk/tests/types/fixtures/protocol_parameters.json';
import * as basic_block_transaction_payload_json from '../../../../sdk/tests/types/fixtures/basic_block_transaction_payload.json';
import * as validation_block_json from '../../../../sdk/tests/types/fixtures/validation_block.json';
import { parseBlock } from '../../lib';

describe('Utils methods', () => {
it('invalid mnemonic error', () => {
Expand Down Expand Up @@ -147,4 +150,15 @@ describe('Utils methods', () => {
BigInt(output.amount) - minimumOutputAmount, creationSlot, targetSlot, protocolParameters)
expect(decayedPotentialMana).toBe(BigInt(2502459));
});

it('compute block work score', async () => {
const block = parseBlock(basic_block_transaction_payload_json.block);
const workScore = Utils.blockWorkScore(block, protocol_parameters.params.workScoreParameters);
expect(workScore).toEqual(basic_block_transaction_payload_json.workScore);

const validationBlock = parseBlock(validation_block_json.block);
const validationBlockWorkScore = Utils.blockWorkScore(validationBlock, protocol_parameters.params.workScoreParameters);
expect(validationBlockWorkScore).toEqual(0);
});

});
12 changes: 11 additions & 1 deletion bindings/python/iota_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from iota_sdk.types.common import HexStr
from iota_sdk.types.decayed_mana import DecayedMana
from iota_sdk.types.payload import Transaction, SignedTransactionPayload
from iota_sdk.types.node_info import ProtocolParameters
from iota_sdk.types.node_info import ProtocolParameters, WorkScoreParameters
from iota_sdk.types.output import Output
from iota_sdk.types.output_id import OutputId
from iota_sdk.types.unlock import Unlock
Expand Down Expand Up @@ -286,6 +286,16 @@ def shimmer_mainnet_protocol_parameters() -> ProtocolParameters:
return ProtocolParameters.from_dict(
_call_method('shimmerMainnetProtocolParameters'))

@staticmethod
def block_work_score(
block: Block, work_score_parameters: WorkScoreParameters) -> int:
"""Returns the work score of a block.
"""
return _call_method('blockWorkScore', {
'block': block,
'workScoreParameters': work_score_parameters,
})


class UtilsError(Exception):
"""A utils error."""
Expand Down
22 changes: 12 additions & 10 deletions bindings/python/tests/test_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,24 @@
# SPDX-License-Identifier: Apache-2.0

import json
# from iota_sdk import Block, ProtocolParameters
from iota_sdk import Block, ProtocolParameters, Utils

protocol_params_json = {}
with open('../../sdk/tests/types/fixtures/protocol_parameters.json', "r", encoding="utf-8") as params:
protocol_params_json = json.load(params)


# def test_basic_block_tagged_data_payload():
# basic_block_tagged_data_payload_json = {}
# with open('../../sdk/tests/types/fixtures/basic_block_tagged_data_payload.json', "r", encoding="utf-8") as payload:
# basic_block_tagged_data_payload_json = json.load(payload)
# block = Block.from_dict(basic_block_tagged_data_payload_json['block'])
# protocol_params = ProtocolParameters.from_dict(
# protocol_params_json['params'])
# expected_id = basic_block_tagged_data_payload_json['id']
# assert block.id(protocol_params) == expected_id
def test_basic_block_tagged_data_payload():
basic_block_tagged_data_payload_json = {}
with open('../../sdk/tests/types/fixtures/basic_block_tagged_data_payload.json', "r", encoding="utf-8") as payload:
basic_block_tagged_data_payload_json = json.load(payload)
block = Block.from_dict(basic_block_tagged_data_payload_json['block'])
protocol_params = ProtocolParameters.from_dict(
protocol_params_json['params'])
expected_id = basic_block_tagged_data_payload_json['id']
assert block.id(protocol_params) == expected_id
assert Utils.block_work_score(
block, protocol_params.work_score_parameters) == basic_block_tagged_data_payload_json['workScore']


# def test_basic_block_transaction_payload():
Expand Down
Loading