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

Feature/lit 2407 js sdk add timestamp on each handshake to alert for when we #349

Closed
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
62 changes: 32 additions & 30 deletions README.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions apps/html/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!-- (DO NOT EDIT!) (HTML) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-html.mjs Thu, 08 Feb 2024 14:41:27 GMT -->
<!-- (DO NOT EDIT!) (HTML) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-html.mjs Thu, 08 Feb 2024 23:45:57 GMT -->
<!DOCTYPE html>
<html lang="en">
<head>
Expand Down Expand Up @@ -62,7 +62,7 @@
</style>
</head>
<body>
(HTML) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-html.mjs Thu, 08 Feb 2024 14:41:27 GMT
(HTML) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-html.mjs Thu, 08 Feb 2024 23:45:57 GMT

<!-- ==================== ALL EXPORTED VANILLA LIBRARIES ==================== -->
<script src="dist/packages/access-control-conditions-vanilla/access-control-conditions.js"></script>
Expand Down
2 changes: 1 addition & 1 deletion apps/react/src/app/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1879,7 +1879,7 @@ pre {
`,
}}
/>
(REACT) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-react.mjs Thu, 08 Feb 2024 14:41:27 GMT
(REACT) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-react.mjs Thu, 08 Feb 2024 23:45:58 GMT
<div id="root"></div>
<pre><code id="result"></code></pre>
</>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import path from 'path';
import { success, fail, testThis } from '../../tools/scripts/utils.mjs';
import * as LitJsSdk from '@lit-protocol/lit-node-client';
import { LocalStorage } from 'node-localstorage';

export async function main() {
const client = new LitNodeClient({
litNetwork: globalThis.LitCI.network,
debug: globalThis.LitCI.debug,
minNodeCount: globalThis.LitCI.minNodeCount,
checkNodeAttestation: globalThis.LitCI.sevAttestation,
storageProvider: {
provider: new LocalStorage('./storage.test.db'),
},
});

await client.connect();
let blockhash = await client.getLatestBlockhash();
await Promise.resolve(
new Promise((resolve, reject) => {
setTimeout(resolve, 40_000);
})
);
let updatedBlockhash = await client.getLatestBlockhash();

if (blockhash === updatedBlockhash) {
return fail('block hash should be updated from handshake');
}
console.log('block hashes: ', blockhash, updatedBlockhash);
return success('block hash updates after expiration period');
}

await testThis({ name: path.basename(import.meta.url), fn: main });
2 changes: 1 addition & 1 deletion e2e-nodejs/loader.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ if (loadEnv) {
});

await litNodeClient.connect();
let nonce = litNodeClient.getLatestBlockhash();
let nonce = await litNodeClient.getLatestBlockhash();
console.log('GENERATED NONCE: ', nonce);

const domain = 'localhost';
Expand Down
26 changes: 13 additions & 13 deletions lit.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@
"debug": true,
"sevAttestation": false,
"CONTROLLER_AUTHSIG": {
"sig": "0x8234b6ab642c2f8d2edbd0adf7fafa25355c972bf5a5071035e4aad45eeba5f405ffbac757b07b8c9cbd073bc3589cad40af87373fa2a98278f45f3033a366b11b",
"sig": "0xa9307d3af0d7fbaebb9997405b85ee266d2aaffdee18a940301307b6123d661531a27d07ed4e7dc4cb9a9682a6608ab52a20ae3cebaab0811e7be42239ca45311b",
"derivedVia": "web3.eth.personal.sign",
"signedMessage": "localhost wants you to sign in with your Ethereum account:\n0xeF71c2604f17Ec6Fc13409DF24EfdC440D240d37\n\nThis is a test statement. You can put anything you want here.\n\nURI: https://localhost/login\nVersion: 1\nChain ID: 1\nNonce: 0x1f89d12f7313557abbe9ef60f6cdb2fb3d276a05609dbf984f5ab881fa837b33\nIssued At: 2024-02-06T21:34:17.641Z\nExpiration Time: 2024-02-06T22:34:17.635Z",
"signedMessage": "localhost wants you to sign in with your Ethereum account:\n0xeF71c2604f17Ec6Fc13409DF24EfdC440D240d37\n\nThis is a test statement. You can put anything you want here.\n\nURI: https://localhost/login\nVersion: 1\nChain ID: 1\nNonce: 0xc34b7a10d2e99b93ec6976e42287bad2db18b81431ab39e1751f44cd82a83b61\nIssued At: 2024-02-07T22:49:11.088Z\nExpiration Time: 2024-02-07T23:49:11.083Z",
"address": "0xeF71c2604f17Ec6Fc13409DF24EfdC440D240d37"
},
"CONTROLLER_WALLET": {
Expand All @@ -59,8 +59,8 @@
"_events": [],
"_emitted": {
"block": -2,
"t:0x24fc5489c0e792f4975646d89f3c96eccd621dcb688fdb97e06d5c45d1057e7e": 1711201,
"t:0x5690c38801ac95e7e14f5ea60e36cab6f91ba1314345b2c0bcc57878c27a9078": 1711204
"t:0x3caf69c3067b37a6de80553c7fb79d04c4ca80bf9391d4eb19ae20250370628e": 1719289,
"t:0x3bd36a3b59f1f504eab0869f98be9bce1c4b0904fd95f0d18ccdb83ad660440f": 1719290
},
"disableCcipRead": false,
"formatter": {
Expand All @@ -77,15 +77,15 @@
},
"anyNetwork": false,
"_networkPromise": {},
"_maxInternalBlockNumber": 1711203,
"_maxInternalBlockNumber": 1719288,
"_lastBlockNumber": -2,
"_maxFilterBlockRange": 10,
"_pollingInterval": 4000,
"_fastQueryDate": 1707255280186,
"_fastQueryDate": 1707346152736,
"connection": {
"url": "https://chain-rpc.litprotocol.com/http"
},
"_nextId": 75,
"_nextId": 73,
"_eventLoopCache": {
"detectNetwork": null,
"eth_chainId": null,
Expand All @@ -96,18 +96,18 @@
"name": "unknown"
},
"_internalBlockNumber": {},
"_fastBlockNumber": 1711203,
"_fastBlockNumber": 1719288,
"_fastBlockNumberPromise": {}
}
},
"PKP_INFO": {
"tokenId": "0x6cafa5604d3dac3ed39533bd399609d15553e5063cf699432477d9c35784bb2d",
"publicKey": "0439068de07bcc4fed3a1192a7d3395b3834c71fb7f5dfd78c9e658cb3ad7a4c243960e7bc009cb7c47cbfced47d64b63361e61c506b2ddba3a73f1de4a41753d7",
"ethAddress": "0x3C7da8933788e1a293CA76Cb65B21174475e4A51"
"tokenId": "0x56eddc026ffe0a196d0cd52f89099c75064aee4dfb47b018361659f35b9b941b",
"publicKey": "04f824bcb46d9a2bc44a15f0ecfb2a00bf793d5d1133cf6ba4341ad9648d362fad4ea78c2003dd79e12f5f576ad889bd81d393841c75d8aa4e56fbca4e3cca2bc1",
"ethAddress": "0xb65e59Ccf736072c67c0cbd7b76d275732F0A9BD"
},
"AUTH_METHOD_PKP_INFO": {
"publicKey": "04097dfb08502ed5a3217d04323ab86c3922bebe09a8917e226cb8664884c6bd31d2cd7c2ba4de9ea029b21280454473e78e596986a6bf981b867b62404971c12f",
"ethAddress": "0x577Bd2bF2069129013b8922dE2e02a28fe08c11f",
"publicKey": "048970ced45d315209a08927cb4b4b02fef41dc4c119e948d5a28081297223d8ea91010781854d2505341c891598641f0806888249d7d83a7df657cc8152549438",
"ethAddress": "0x0Df70921D2a2E2378E9B023c31FEDdb6D5a5b19B",
"authMethod": {
"authMethodId": "0x170d13600caea2933912f39a0334eca3d22e472be203f937c4bad0213d92ed71",
"authMethodType": 1
Expand Down
14 changes: 11 additions & 3 deletions packages/constants/src/lib/constants/autogen_internal.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
// Last Modified: 2024-02-08 14:39:50
// Last Modified: 2024-02-08 23:44:16
// This file is auto-generated by tools/scripts/gen-internal-dev.mjs
export const INTERNAL_DEV = [
'https://167.114.17.205:443',
'https://167.114.17.204:443',
'https://199.115.117.115:443',
'https://167.114.17.203:443',
'https://64.131.85.106:443',
'https://64.131.85.108:443',
'https://167.114.17.201:443',
'https://167.114.17.202:443',
];

Expand All @@ -13,8 +17,12 @@ export const INTERNAL_DEFAULT_CONFIG = {
minNodeCount: 2,
debug: true,
bootstrapUrls: [
'https://167.114.17.205:443',
'https://167.114.17.204:443',
'https://199.115.117.115:443',
'https://167.114.17.203:443',
'https://64.131.85.106:443',
'https://64.131.85.108:443',
'https://167.114.17.201:443',
'https://167.114.17.202:443',
],
litNetwork: 'internalDev',
Expand Down
49 changes: 49 additions & 0 deletions packages/core/src/lib/lit-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export class LitCore {
networkPubKeySet: string | null;
hdRootPubkeys: string[] | null;
latestBlockhash: string | null;
lastblockHashRetrieved: number | null;

// ========== Constructor ==========
constructor(args: any[LitNodeClientConfig | CustomNetwork | any]) {
Expand Down Expand Up @@ -151,6 +152,7 @@ export class LitCore {
this.networkPubKeySet = null;
this.hdRootPubkeys = null;
this.latestBlockhash = null;
this.lastblockHashRetrieved = null;
// -- set bootstrapUrls to match the network litNetwork unless it's set to custom
this.setCustomBootstrapUrls();

Expand Down Expand Up @@ -305,7 +307,42 @@ export class LitCore {
stakingContract.on('StateChanged', async (state: StakingStates) => {
log(`New state detected: "${state}"`);
if (state === StakingStates.NextValidatorSetLocked) {
log(
'State found to be new validator set locked, checking validator set'
);
const oldNodeUrls: string[] = [...this.config.bootstrapUrls].sort();
await this.setNewConfig();
const currentNodeUrls: string[] = this.config.bootstrapUrls.sort();
const delta: string[] = currentNodeUrls.filter((item) =>
oldNodeUrls.includes(item)
);
// if the sets differ we reconnect.
if (delta.length > 1) {
// check if the node sets are non matching and re connect if they do not.
/*
TODO: While this covers most cases where a node may come in or out of the active
set which we will need to re attest to the execution enviorments.
The sdk currently does not know if there is an active network operation pending.
Such that the state when the request was sent will now mutate when the response is sent back.
The sdk should be able to understand its current execution enviorment and wait on an active
network request to the previous epoch's node set before changing over.

*/
log(
'Active validator sets changed, new validators ',
delta,
'starting node connection'
);
this.connectedNodes =
await this._runHandshakeWithBootstrapUrls().catch(
(err: NodeClientErrorV0 | NodeClientErrorV1) => {
logError(
'Error while attempting to reconnect to nodes after epoch transition: ',
err.message
);
}
);
}
}
});
}
Expand Down Expand Up @@ -350,10 +387,21 @@ export class LitCore {
// -- handshake with each node
await this.setNewConfig();
await this.listenForNewEpoch();
await this._runHandshakeWithBootstrapUrls();
};

/**
*
* @returns {Promise<any>}
*/

_runHandshakeWithBootstrapUrls = async (): Promise<any> => {
// -- handshake with each node
const requestId = this.getRequestId();

// reset connectedNodes for the new handshake operation
this.connectedNodes = new Set();

if (this.config.bootstrapUrls.length <= 0) {
throwError({
message: `Failed to get bootstrapUrls for network ${this.config.litNetwork}`,
Expand Down Expand Up @@ -500,6 +548,7 @@ export class LitCore {
});
}

this.lastblockHashRetrieved = Date.now();
this.ready = true;

log(
Expand Down
27 changes: 24 additions & 3 deletions packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ export class LitNodeClientNodeJs extends LitCore {
throw new Error('Failed to verify capabilities for resource');
}

let nonce = this.getLatestBlockhash();
let nonce = await this.getLatestBlockhash();

// -- get auth sig
let siweMessage = new siwe.SiweMessage({
Expand Down Expand Up @@ -490,8 +490,29 @@ export class LitNodeClientNodeJs extends LitCore {
return LitNodeClientNodeJs.getExpiration();
};

getLatestBlockhash = () => {
return this.latestBlockhash;
/**
* returns the latest block hash.
* will call refresh if the block hash is expired
* @returns {Promise<string>} latest block hash from `handhsake` with the lit network.
*/
getLatestBlockhash = async (): Promise<string> => {
if (!this.ready) {
logError('Client not connected, remember to call connect');
throwError({
message: 'Client not connected',
errorKind: LIT_ERROR.LIT_NODE_CLIENT_NOT_READY_ERROR.kind,
errorCode: LIT_ERROR.LIT_NODE_CLIENT_NOT_READY_ERROR.code,
});
}

if (Date.now() - this.lastblockHashRetrieved! >= 30_000) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we make 30_000 as constant

await this._runHandshakeWithBootstrapUrls().catch((err: any) => {
logError('errror while attempting to update block hash ', err);
});
}

// we are confident in this value being non null so we return
return this.latestBlockhash!;
};

/**
Expand Down