Skip to content

Commit

Permalink
Prefer author_getNextNonce for nonce retrieval (#2576)
Browse files Browse the repository at this point in the history
  • Loading branch information
silva-fj committed Mar 15, 2024
1 parent 303a39a commit 276564a
Show file tree
Hide file tree
Showing 10 changed files with 58 additions and 45 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ gethdata
/log-backup
**/__pycache__/
**/.env

rust-analyzer.json
22 changes: 15 additions & 7 deletions tee-worker/enclave-runtime/src/rpc/worker_api_direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ use itp_sgx_crypto::{
};
use itp_sgx_externalities::SgxExternalitiesTrait;
use itp_stf_executor::{getter_executor::ExecuteGetter, traits::StfShardVaultQuery};
use itp_stf_primitives::types::AccountId;
use itp_stf_state_handler::handle_state::HandleState;
use itp_top_pool_author::traits::AuthorApi;
use itp_types::{DirectRequestStatus, Index, RsaRequest, ShardIdentifier, H256};
Expand All @@ -51,7 +50,7 @@ use its_sidechain::rpc_handler::{
use jsonrpc_core::{serde_json::json, IoHandler, Params, Value};
use lc_scheduled_enclave::{ScheduledEnclaveUpdater, GLOBAL_SCHEDULED_ENCLAVE};
use litentry_macros::if_not_production;
use litentry_primitives::DecryptableRequest;
use litentry_primitives::{DecryptableRequest, Identity};
use log::debug;
use sgx_crypto_helper::rsa3072::Rsa3072PubKey;
use sp_core::Pair;
Expand Down Expand Up @@ -143,6 +142,7 @@ where
let local_top_pool_author = top_pool_author.clone();
let local_state = state.clone();
io.add_sync_method("author_getNextNonce", move |params: Params| {
debug!("worker_api_direct rpc was called: author_getNextNonce");
let local_state = match local_state.clone() {
Some(s) => s,
None =>
Expand All @@ -152,7 +152,7 @@ where
};

match params.parse::<(String, String)>() {
Ok((shard_base58, account_hex)) => {
Ok((shard_base58, identity_hex)) => {
let shard = match decode_shard_from_base58(shard_base58.as_str()) {
Ok(id) => id,
Err(msg) => {
Expand All @@ -161,8 +161,16 @@ where
return Ok(json!(compute_hex_encoded_return_error(error_msg.as_str())))
},
};
let account = match AccountId::from_hex(account_hex.as_str()) {
Ok(acc) => acc,

let account_id = match Identity::from_hex(identity_hex.as_str()) {
Ok(identity) =>
if let Some(account_id) = identity.to_account_id() {
account_id
} else {
return Ok(json!(compute_hex_encoded_return_error(
"Could not retrieve author_getNextNonce calls due to: invalid identity"
)))
},
Err(msg) => {
let error_msg: String = format!(
"Could not retrieve author_getNextNonce calls due to: {:?}",
Expand All @@ -175,11 +183,11 @@ where
match local_state.load_cloned(&shard) {
Ok((mut state, _hash)) => {
let trusted_calls =
local_top_pool_author.get_pending_trusted_calls_for(shard, &account);
local_top_pool_author.get_pending_trusted_calls_for(shard, &account_id);
let pending_tx_count = trusted_calls.len();
#[allow(clippy::unwrap_used)]
let pending_tx_count = Index::try_from(pending_tx_count).unwrap();
let nonce = state.execute_with(|| System::account_nonce(&account));
let nonce = state.execute_with(|| System::account_nonce(&account_id));
let json_value = RpcReturnValue {
do_watch: false,
value: (nonce.saturating_add(pending_tx_count)).encode(),
Expand Down
22 changes: 14 additions & 8 deletions tee-worker/ts-tests/integration-tests/common/di-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { aesKey, decodeRpcBytesAsString, keyNonce } from './call';
import { createPublicKey, KeyObject } from 'crypto';
import WebSocketAsPromised from 'websocket-as-promised';
import { H256, Index } from '@polkadot/types/interfaces';
import { blake2AsHex } from '@polkadot/util-crypto';
import { blake2AsHex, base58Encode } from '@polkadot/util-crypto';
import { createJsonRpcRequest, nextRequestId } from './helpers';

// Send the request to worker ws
Expand Down Expand Up @@ -297,15 +297,21 @@ export async function createSignedTrustedGetterIdGraph(

export const getSidechainNonce = async (
context: IntegrationTestContext,
teeShieldingKey: KeyObject,
primeIdentity: CorePrimitivesIdentity
): Promise<Index> => {
// wait for the nonce to be updated in sidechain
await sleep(5);
const getterPublic = createPublicGetter(context.api, ['nonce', '(LitentryIdentity)'], primeIdentity.toHuman());
const getter = context.api.createType('Getter', { public: getterPublic });
const res = await sendRequestFromGetter(context, teeShieldingKey, getter);
const nonce = context.api.createType('Option<Bytes>', hexToU8a(res.value.toHex())).unwrap();
const request = createJsonRpcRequest(
'author_getNextNonce',
[base58Encode(hexToU8a(context.mrEnclave)), primeIdentity.toHex()],
nextRequestId(context)
);
const res = await sendRequest(context.tee, request, context.api);
const nonceHex = res.value.toHex();
let nonce = 0;

if (nonceHex) {
nonce = context.api.createType('Index', '0x' + nonceHex.slice(2)?.match(/../g)?.reverse().join('')).toNumber();
}

return context.api.createType('Index', nonce);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ describe('Test Vc (direct invocation)', function () {

console.log('assertion: ', assertion);

let currentNonce = (await getSidechainNonce(context, teeShieldingKey, substrateIdentities[index])).toNumber();
let currentNonce = (await getSidechainNonce(context, substrateIdentities[index])).toNumber();
const getNextNonce = () => currentNonce++;
const nonce = getNextNonce();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ describe('Test Identity (bitcoin direct invocation)', function () {
});

step('linking identities (alice bitcoin account)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceBitcoinIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceBitcoinIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const aliceEvmNonce = getNextNonce();
Expand Down Expand Up @@ -210,7 +210,7 @@ describe('Test Identity (bitcoin direct invocation)', function () {
await assertIdGraphHash(context, teeShieldingKey, aliceBitcoinIdentity, idGraph);
});
step('deactivating identity(alice bitcoin account)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceBitcoinIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceBitcoinIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const aliceEvmNonce = getNextNonce();
Expand Down Expand Up @@ -281,7 +281,7 @@ describe('Test Identity (bitcoin direct invocation)', function () {
});

step('activating identity(alice bitcoin account)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceBitcoinIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceBitcoinIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const aliceEvmNonce = getNextNonce();
Expand Down
6 changes: 3 additions & 3 deletions tee-worker/ts-tests/integration-tests/di_evm_identity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ describe('Test Identity (evm direct invocation)', function () {
});

step('linking identities (alice evm account)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceEvmIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceEvmIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const bobEvmNonce = getNextNonce();
Expand Down Expand Up @@ -196,7 +196,7 @@ describe('Test Identity (evm direct invocation)', function () {
await assertIdGraphHash(context, teeShieldingKey, aliceEvmIdentity, idGraph);
});
step('deactivating identity(alice evm account)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceEvmIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceEvmIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const deactivateIdentityRequestParams: {
Expand Down Expand Up @@ -285,7 +285,7 @@ describe('Test Identity (evm direct invocation)', function () {
await assertIdGraphHash(context, teeShieldingKey, aliceEvmIdentity, idGraph);
});
step('activating identity(alice evm account)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceEvmIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceEvmIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const activateIdentityRequestParams: {
Expand Down
32 changes: 14 additions & 18 deletions tee-worker/ts-tests/integration-tests/di_substrate_identity.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { randomBytes, KeyObject } from 'crypto';
import { step } from 'mocha-steps';
import { assert } from 'chai';
import { u8aToHex, u8aToString, bufferToU8a } from '@polkadot/util';
import { u8aToHex, u8aToString } from '@polkadot/util';
import {
assertIdGraphMutationResult,
assertIdGraphHash,
Expand Down Expand Up @@ -77,7 +77,7 @@ describe('Test Identity (direct invocation)', function () {
});

step('linking identities (alice)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const twitterNonce = getNextNonce();
Expand Down Expand Up @@ -249,7 +249,7 @@ describe('Test Identity (direct invocation)', function () {
context
);

let currentNonce = (await getSidechainNonce(context, teeShieldingKey, bobSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, bobSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const twitterIdentity = await buildIdentityHelper('mock_user', 'Twitter', context);
Expand Down Expand Up @@ -299,7 +299,7 @@ describe('Test Identity (direct invocation)', function () {
});

step('linking identity with wrong signature', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;
const evmIdentity = await buildIdentityHelper(context.ethersWallet.alice.address, 'Evm', context);
const evmNetworks = context.api.createType('Vec<Web3Network>', ['Ethereum', 'Bsc']);
Expand Down Expand Up @@ -356,19 +356,15 @@ describe('Test Identity (direct invocation)', function () {

step('linking already linked identity', async function () {
// sleep for a while to make sure the nonce is updated
await sleep(3);

let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const twitterNonce = getNextNonce();
await sleep(10);

const currentNonce = await getSidechainNonce(context, aliceSubstrateIdentity);
const twitterIdentity = await buildIdentityHelper('mock_user', 'Twitter', context);
const [twitterValidation] = await buildValidations(
context,
[aliceSubstrateIdentity],
[twitterIdentity],
twitterNonce,
currentNonce.toNumber(),
'twitter'
);
const twitterNetworks = context.api.createType('Vec<Web3Network>', []);
Expand All @@ -377,7 +373,7 @@ describe('Test Identity (direct invocation)', function () {
const linkIdentityCall = await createSignedTrustedCallLinkIdentity(
context.api,
context.mrEnclave,
context.api.createType('Index', twitterNonce),
currentNonce,
new PolkadotSigner(context.substrateWallet.alice),
aliceSubstrateIdentity,
twitterIdentity.toHex(),
Expand Down Expand Up @@ -405,7 +401,7 @@ describe('Test Identity (direct invocation)', function () {
});

step('deactivating linked identities', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const deactivateIdentityRequestParams: {
Expand Down Expand Up @@ -516,7 +512,7 @@ describe('Test Identity (direct invocation)', function () {
await assertIdGraphHash(context, teeShieldingKey, aliceSubstrateIdentity, idGraph);
});
step('activating linked identities', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const activateIdentityRequestParams: {
Expand Down Expand Up @@ -642,7 +638,7 @@ describe('Test Identity (direct invocation)', function () {
});

step('setting identity network(alice)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;
const eveSubstrateIdentity = await buildIdentityHelper(
u8aToHex(context.substrateWallet.eve.addressRaw),
Expand Down Expand Up @@ -705,7 +701,7 @@ describe('Test Identity (direct invocation)', function () {
});

step('setting incompatible identity network(alice)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;
const eveSubstrateIdentity = await buildIdentityHelper(
u8aToHex(context.substrateWallet.eve.addressRaw),
Expand Down Expand Up @@ -768,7 +764,7 @@ describe('Test Identity (direct invocation)', function () {
context
);

let currentNonce = (await getSidechainNonce(context, teeShieldingKey, bobSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, bobSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const deactivateIdentityRequestParams: {
Expand Down Expand Up @@ -821,7 +817,7 @@ describe('Test Identity (direct invocation)', function () {
context
);

let currentNonce = (await getSidechainNonce(context, teeShieldingKey, charlieSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, charlieSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const requestIdentifier = `0x${randomBytes(32).toString('hex')}`;
Expand Down
4 changes: 2 additions & 2 deletions tee-worker/ts-tests/integration-tests/di_vc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ describe('Test Vc (direct invocation)', function () {
});

step('linking identities (alice)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const twitterNonce = getNextNonce();
Expand Down Expand Up @@ -136,7 +136,7 @@ describe('Test Vc (direct invocation)', function () {

mockAssertions.forEach(({ description, assertion }) => {
step(`request vc payload : ${JSON.stringify(assertion)} (alice)`, async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;
const nonce = getNextNonce();
const requestIdentifier = `0x${randomBytes(32).toString('hex')}`;
Expand Down
4 changes: 2 additions & 2 deletions tee-worker/ts-tests/integration-tests/dr_vc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ describe('Test Vc (direct request)', function () {
});

step('linking identities (alice)', async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;

const twitterNonce = getNextNonce();
Expand Down Expand Up @@ -137,7 +137,7 @@ describe('Test Vc (direct request)', function () {

mockBatchAssertion.forEach(({ description, assertion }) => {
step(`request vc payload: ${JSON.stringify(assertion)} (alice)`, async function () {
let currentNonce = (await getSidechainNonce(context, teeShieldingKey, aliceSubstrateIdentity)).toNumber();
let currentNonce = (await getSidechainNonce(context, aliceSubstrateIdentity)).toNumber();
const getNextNonce = () => currentNonce++;
const nonce = getNextNonce();
const requestIdentifier = `0x${randomBytes(32).toString('hex')}`;
Expand Down
3 changes: 2 additions & 1 deletion tee-worker/ts-tests/integration-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"check-format": "prettier --check .",
"format": "prettier --write .",
"pretest": "eslint .",
"test": "mocha --exit --sort -r ts-node/register --loader=ts-node/esm"
"test": "mocha --exit --sort -r ts-node/register --loader=ts-node/esm",
"check-types": "tsc --noEmit"
},
"dependencies": {
"@litentry/vc-schema-validator": "^0.0.1",
Expand Down

0 comments on commit 276564a

Please sign in to comment.