diff --git a/src.ts/_tests/golden-capture.ts b/src.ts/_tests/golden-capture.ts index 30fde5c0..41d32515 100644 --- a/src.ts/_tests/golden-capture.ts +++ b/src.ts/_tests/golden-capture.ts @@ -536,7 +536,7 @@ async function transactions(): Promise { }); await cap(o, "signed", async () => { const w = new Wallet({ key: PRIV_A, prefix: PREFIX }); - const signed = await w.signTransaction(base); + const signed = await w.signTransaction({ ...base, to: w.address }); const parsed = Transaction.from(signed); return { serialized: signed, diff --git a/src.ts/_tests/test-contract.ts b/src.ts/_tests/test-contract.ts index 63353e01..fa221b20 100644 --- a/src.ts/_tests/test-contract.ts +++ b/src.ts/_tests/test-contract.ts @@ -12,7 +12,7 @@ import { networkIdToPrefix } from "../address/index.js"; const TIMEOUT_PERIOD = 120000; const tesSignedTransaction = - "0xf8ce800a830f423f0496ce276773ac97d16855a3c8faa45399136b56d419486081c880b8ab54bc60412c90c104a89865a43c33f335836bcb473f0cd477ecb2c82e6310676c87b708e3971d009b4a04e518f12454c3ee1aebc19a6b7df00076b834b692b7432611f3dafff0f422dfbae722ba4b989cfc82fee2e539fbbf21d652ea587df59e8421a3a8bc8ca2ba35033598954c54e10c00315484db568379ce94f9c894e3e6e4c7ee216676b713ca892d9b26746ae902a772e217a6a8bb493ce2bb313cf0cb66e76765d4c45ec6b68600"; + "0xf8ce800a830f423f0396ab03a5fd22b9bee8b8ab877c86e0a2c21765e1d5bfc581c880b8abcee66d9ba5aed1a813379ac23b7a326830bcbca9501b9c0d1e1214d71814ec96f41330d1abdd7a56babda62a3eaa1c376699a64e152b6c928064fe78973123e0d8a3a6effbe6f809384fd1af97e7094fd839d6f92c379707f177d4bddf13cac611c10802c02a0dd7f2f4bc1a248a7df02600315484db568379ce94f9c894e3e6e4c7ee216676b713ca892d9b26746ae902a772e217a6a8bb493ce2bb313cf0cb66e76765d4c45ec6b68600"; const testWalletPhrase = "better artwork flavor fish solve deer orient spread adapt doll attack hour sort copper super income bacon engine skate ill similar wink crack club"; const testSeed = @@ -55,12 +55,12 @@ const baseWallet = new BaseWallet({ }); const randomWallet = Wallet.createRandom(networkIdToPrefix(3), provider); const transaction = Transaction.from({ - to: "0xce276773ac97d16855a3c8faa45399136b56d4194860", + to: baseWalletAddress, value: 200n, nonce: 0, energyLimit: 999999n, energyPrice: 10n, - networkId: 4, + networkId: 3, }); // The provider is shared by every suite in this file, so it has to outlive diff --git a/src.ts/_tests/test-core-units.ts b/src.ts/_tests/test-core-units.ts index fe3eaef9..efb448b9 100644 --- a/src.ts/_tests/test-core-units.ts +++ b/src.ts/_tests/test-core-units.ts @@ -76,8 +76,8 @@ describe("Core denomination ladder", () => { it("treats ore as the atomic unit with no fractional part", () => { assert.equal(parseUnits("1", "ore"), BigInt(1)); - // Sub-ore precision is truncated rather than rounded or rejected. - assert.equal(parseUnits("1.9", "ore"), BigInt(1)); + // A fractional ore cannot be represented. + assert.throws(() => parseUnits("1.9", "ore"), /too many decimals/); assert.equal(formatUnits(BigInt(1), "ore"), "1"); }); @@ -116,7 +116,7 @@ describe("Core denominations reject Ethereum names", () => { describe("unit conversion by explicit decimals", () => { it("accepts a decimal count in place of a unit name", () => { assert.equal(parseUnits("1.5", 6), BigInt(1500000)); - assert.equal(parseUnits("1.5", 0), BigInt(1)); + assert.throws(() => parseUnits("1.5", 0), /too many decimals/); assert.equal(formatUnits(BigInt(1500000), 6), "1.5"); }); @@ -127,7 +127,8 @@ describe("unit conversion by explicit decimals", () => { it("agrees with the named units", () => { for (const [unit, decimals] of LADDER) { - assert.equal(parseUnits("2.5", unit), parseUnits("2.5", decimals), unit); + const exact = decimals === 0 ? "2" : "2.5"; + assert.equal(parseUnits(exact, unit), parseUnits(exact, decimals), unit); const value = BigInt(10) ** BigInt(18); assert.equal( formatUnits(value, unit), @@ -176,14 +177,31 @@ describe("unit conversion input handling", () => { assert.equal(parseUnits("1e-18", "core"), BigInt(1)); }); - it("truncates precision beyond the unit's decimals", () => { - // 19 decimal places against an 18 decimal unit: the extra digit is - // dropped rather than rounding or throwing. - assert.equal( - parseUnits("1." + "1".repeat(19), "core"), - BigInt("1111111111111111111"), - ); - assert.equal(parseUnits("1.9999", 2), BigInt(199)); + it("rejects unrepresentable amounts and accepts extra trailing zeros", () => { + for (const value of [ + "1." + "1".repeat(19), + "0.0000000000000000001", + "1e-19", + "-1e-19", + ]) { + assert.throws(() => parseXCB(value), /too many decimals/); + assert.throws(() => parseUnits(value), /too many decimals/); + } + assert.throws(() => parseUnits("1.9999", 2), /too many decimals/); + assert.equal(parseUnits("1.2300", 2), 123n); + assert.equal(parseUnits("1.000", "ore"), 1n); + }); + + it("keeps scientific amounts exact and bounds exponent expansion", () => { + assert.equal(parseXCB("1.000000000000000001e0"), 1000000000000000001n); + assert.equal(parseUnits("9007199254740993e0", "ore"), 9007199254740993n); + assert.equal(parseUnits("-12345E-2", 2), -12345n); + assert.equal(parseUnits(".0012e+4", 0), 12n); + assert.equal(parseUnits("+1.234e+3", 0), 1234n); + assert.equal(parseXCB("10000000000000000000e-37"), 1n); + assert.throws(() => parseXCB("1e1000000"), /overflow/); + assert.throws(() => parseXCB("1e-1000000"), /too many decimals/); + assert.equal(parseXCB("0e1000000"), 0n); }); it("requires the parse input to be a string", () => { @@ -228,17 +246,6 @@ describe("unit conversion input handling", () => { } }); - it("still truncates legitimate excess precision", () => { - // Rejecting malformed input must not break the truncation of a single - // over-long fraction. - assert.equal( - parseUnits("1." + "1".repeat(19), "core"), - BigInt("1111111111111111111"), - ); - assert.equal(parseUnits("1.9", "ore"), BigInt(1)); - assert.equal(parseUnits("1.9999", 2), BigInt(199)); - }); - it("accepts the full range of BigNumberish for formatting", () => { assert.equal(formatUnits("1000000000000000000", "core"), "1.0"); assert.equal(formatUnits(BigInt(10) ** BigInt(18), "core"), "1.0"); diff --git a/src.ts/_tests/test-default-provider.ts b/src.ts/_tests/test-default-provider.ts new file mode 100644 index 00000000..f72cadc7 --- /dev/null +++ b/src.ts/_tests/test-default-provider.ts @@ -0,0 +1,116 @@ +import assert from "node:assert/strict"; +import { + getDefaultProvider, + JsonRpcProvider, + Network, + WebSocketProvider, +} from "../index.js"; + +import type { Networkish } from "../providers/index.js"; + +describe("Core default RPC profiles", () => { + const profiles = [ + { + name: "mainnet", + id: 1, + url: "https://xcbapi.coreblockchain.net/", + inputs: [undefined, "mainnet", "cb", 1, 1n], + }, + { + name: "devin", + id: 3, + url: "https://xcbapi.corecoin.cc/", + inputs: ["devin", "testnet", "ab", 3, 3n], + }, + ]; + + for (const { name, id, url, inputs } of profiles) { + it(`routes each form of ${name} directly to its Core endpoint`, () => { + const networks: Array = [ + ...inputs, + new Network(name, id), + { name, networkId: id }, + ]; + for (const network of networks) { + const provider = getDefaultProvider(network); + try { + assert.ok(provider instanceof JsonRpcProvider); + assert.equal(provider._getConnection().url, url); + } finally { + provider.destroy(); + } + } + }); + + it(`verifies the RPC network ID for ${name}`, async () => { + const provider = getDefaultProvider(name); + assert.ok(provider instanceof JsonRpcProvider); + let reportedId = id; + provider._send = async (payload) => { + assert.ok(!Array.isArray(payload)); + assert.equal(payload.method, "xcb_networkId"); + return [{ id: payload.id, result: "0x" + reportedId.toString(16) }]; + }; + try { + assert.equal((await provider.getNetwork()).networkId, BigInt(id)); + reportedId = id === 1 ? 3 : 1; + await assert.rejects(provider.getNetwork(), { code: "NETWORK_ERROR" }); + } finally { + provider.destroy(); + } + }); + } + + it("requires an explicit endpoint outside the two public networks", () => { + for (const network of [ + "homestead", + "ropsten", + "sepolia", + "matic", + "private", + "ce", + 1337, + new Network("ropsten", 3), + new Network("devin", 1), + ]) { + assert.throws( + () => getDefaultProvider(network), + /unknown network|no public Core RPC/, + ); + } + }); + + it("rejects legacy backend selection for named profiles", () => { + assert.throws( + () => getDefaultProvider("mainnet", { exclusive: "infura" }), + /backend options/, + ); + }); + + it("connects directly to an explicitly supplied HTTP URL or WebSocket", async () => { + const url = "http://localhost:8545/"; + const http = getDefaultProvider(url); + try { + assert.ok(http instanceof JsonRpcProvider); + assert.equal(http._getConnection().url, url); + } finally { + http.destroy(); + } + + const socket = { + onopen: null, + onmessage: null, + onerror: null, + readyState: 0, + send() {}, + close() {}, + }; + const ws = getDefaultProvider(socket); + try { + assert.ok(ws instanceof WebSocketProvider); + assert.equal(ws.websocket, socket); + } finally { + await ws.destroy(); + } + }); +}); diff --git a/src.ts/_tests/test-devin-fixtures.ts b/src.ts/_tests/test-devin-fixtures.ts index 95b757a4..c155feb4 100644 --- a/src.ts/_tests/test-devin-fixtures.ts +++ b/src.ts/_tests/test-devin-fixtures.ts @@ -98,6 +98,22 @@ describe("Devin transaction responses", () => { ); assert.equal(tx.energyPrice, 10_000_000_000n); assert.equal(tx.networkId, 3n); + assert.equal(tx.index, 0); + }); + + it("reads nonzero RPC transaction indexes and preserves a normalized index", () => { + const raw = { ...swapResponse, transactionIndex: "0x10" }; + assert.equal(formatTransactionResponse(raw).index, 16); + assert.equal(formatTransactionResponse({ ...raw, index: 0 }).index, 0); + }); + + it("leaves the index undefined when a pending transaction has no position", () => { + const { transactionIndex, ...fields } = swapResponse; + const pending = { ...fields, blockHash: null, blockNumber: null }; + for (const raw of [pending, { ...pending, transactionIndex: null }]) { + const tx = formatTransactionResponse(raw); + assert.equal(tx.index, undefined); + } }); it("re-serializes to the hash the network assigned", () => { diff --git a/src.ts/_tests/test-live-devin.ts b/src.ts/_tests/test-live-devin.ts index 1befde0d..485a8332 100644 --- a/src.ts/_tests/test-live-devin.ts +++ b/src.ts/_tests/test-live-devin.ts @@ -75,12 +75,14 @@ const wxcbAbi = [ assert.ok(tx); assert.equal(tx.from, SWAP_SENDER); assert.equal(tx.networkId, 3n); + assert.equal(tx.index, 0); assert.ok(tx.energyPrice > 0n); assert.equal(Transaction.from(tx).hash, SWAP_HASH); const block = await provider.getBlock(SWAP_BLOCK, true); assert.equal(block?.prefetchedTransactions[0].hash, SWAP_HASH); assert.equal(block?.prefetchedTransactions[0].networkId, 3n); + assert.equal(block?.prefetchedTransactions[0].index, tx.index); const receipt = await provider.getTransactionReceipt(SWAP_HASH); assert.equal(receipt?.status, 1); diff --git a/src.ts/_tests/test-mnemonic-hd.ts b/src.ts/_tests/test-mnemonic-hd.ts index 49fd9638..604f7e8e 100644 --- a/src.ts/_tests/test-mnemonic-hd.ts +++ b/src.ts/_tests/test-mnemonic-hd.ts @@ -468,6 +468,27 @@ describe("Mnemonic: seed derivation and password", () => { assert.equal(mnemonic.computeSeed(), seed, "deterministic"); }); + it("matches BIP-39 with a Unicode passphrase on every mnemonic entry point", () => { + const phrase = "abandon ".repeat(11) + "about"; + // Independent PBKDF2-HMAC-SHA512 vector over NFKD UTF-8. + const expected = + "0d02d87e72ac4f3c2f2b782309d759672b1bfdc60263be08c188007731870434ef952d7061cf5bcef1301d75d45ae91d2986ff844829bd15607a26851f8f4ca6"; + for (const password of ["Café 🔑", "Cafe\u0301 🔑"]) { + assert.equal( + Mnemonic.fromPhrase({ phrase, password }).computeSeed(), + expected, + ); + assert.equal( + HDNodeWallet.mnemonicToSeed(phrase.split(" ").join("\u3000"), password), + expected, + ); + assert.equal( + Wallet.fromPhrase({ phrase, password, prefix: PREFIX }).address, + Wallet.fromSeed({ seed: expected, prefix: PREFIX }).address, + ); + } + }); + it("gives every strength its own seed", () => { const seeds = STRENGTHS.map(({ bytes }) => Mnemonic.fromEntropy("0x" + "0f".repeat(bytes)).computeSeed(), @@ -1251,6 +1272,29 @@ describe("HDNodeWallet: network prefixes", () => { }); describe("HDNodeWallet: seed input handling", () => { + it("redacts invalid seeds from error details on both public entry points", () => { + const marker = "abcdef012345"; + for (const seed of [ + marker, + marker.repeat(12), + marker + "z", + new Uint8Array([0xab]), + { secret: marker }, + ]) { + for (const create of [Wallet.fromSeed, HDNodeWallet.fromSeed]) { + assert.throws( + () => create({ seed: seed as any, prefix: PREFIX }), + (err: any) => + err.code === "INVALID_ARGUMENT" && + err.argument === "seed" && + err.value === "[ REDACTED ]" && + !err.message.includes(marker) && + !JSON.stringify(err).includes(marker), + ); + } + } + }); + it("derives the same wallet from a seed given as hex text or bytes", () => { const expected = hd(); assert.equal( diff --git a/src.ts/_tests/test-network-consistency.ts b/src.ts/_tests/test-network-consistency.ts index 0547ec61..896e0cba 100644 --- a/src.ts/_tests/test-network-consistency.ts +++ b/src.ts/_tests/test-network-consistency.ts @@ -126,50 +126,49 @@ describe("sender recovery honours the transaction's network id", () => { } }); - it("recovers a differently-prefixed address when wallet and network disagree", async () => { - // The prefix comes from the transaction's networkId, not from the - // signer, so signing a testnet transaction with a mainnet wallet - // recovers the same key under the testnet prefix. Same identity, - // different rendering - callers must keep the two aligned. - const wallet = new Wallet({ key: KEY, prefix: "cb" }); - const tx = Transaction.from({ - networkId: 3, - nonce: 1, - energyLimit: 21000, - energyPrice: 1000, - value: 0, - }); - const parsed = Transaction.from(await wallet.signTransaction(tx)); - - assert.notEqual(parsed.from, wallet.address, "prefix must differ"); - assert.equal(extractPrefix(parsed.from!), "ab", "uses the tx network"); - assert.equal(extractPrefix(wallet.address), "cb"); - assert.equal( - parsed.from!.substring(6), - wallet.address.substring(6), - "same underlying key body", - ); + it("rejects requests for a different wallet network before signing", async () => { + for (const [networkId, prefix] of [ + [1, "ab"], + [3, "cb"], + ] as const) { + const wallet = new Wallet({ key: KEY, prefix }); + await assert.rejects( + wallet.signTransaction({ networkId, from: wallet.address }), + /network does not match wallet/, + ); + } }); - it("refuses to recover a sender for an unassigned network id", async () => { + it("rejects an unassigned network id before signing", async () => { const wallet = new Wallet({ key: KEY, prefix: "cb" }); for (const networkId of UNASSIGNED_IDS) { - const tx = Transaction.from({ - networkId, - nonce: 1, - energyLimit: 21000, - energyPrice: 1000, - value: 0, - }); - const serialized = await wallet.signTransaction(tx); - assert.throws( - () => Transaction.from(serialized).from, + await assert.rejects( + wallet.signTransaction({ networkId }), /bad networkId/, - `networkId ${networkId}`, ); } }); + it("checks the recipient network and permits network-independent destinations", async () => { + const { wallet } = signedTransaction(3, "ab"); + const other = new Wallet({ key: OTHER_KEY, prefix: "cb" }); + await assert.rejects( + wallet.signTransaction({ networkId: 3, to: other.address }), + /recipient address does not match/, + ); + for (const to of [ + null, + "0x" + "00".repeat(22), + "0x" + "00".repeat(21) + "01", + ]) { + const parsed = Transaction.from( + await wallet.signTransaction({ networkId: 3, to }), + ); + assert.equal(parsed.to, to); + assert.equal(parsed.from, wallet.address); + } + }); + it("preserves the network id through a serialization round trip", async () => { for (const { networkId, prefix } of VALID_IDS) { const { wallet, tx } = signedTransaction(networkId, prefix); @@ -197,7 +196,8 @@ describe("sender recovery honours the transaction's network id", () => { const one = await wallet.signTransaction( Transaction.from({ ...base, networkId: 1 }), ); - const three = await wallet.signTransaction( + const devinWallet = new Wallet({ key: KEY, prefix: "ab" }); + const three = await devinWallet.signTransaction( Transaction.from({ ...base, networkId: 3 }), ); assert.notEqual(one, three); @@ -374,24 +374,19 @@ describe("network registry", () => { } }); - it("keeps the legacy network names resolvable", () => { - // These shipped in the registry before Core's own names were added. - // They stay registered so existing code that asks for them by name - // keeps working, even though they are not Core networks. - const legacy: Array<[string, number]> = [ - ["ropsten", 3], - ["rinkeby", 4], - ["goerli", 5], - ["kovan", 42], - ["sepolia", 11155111], - ["classic", 61], - ["classicKotti", 6], - ["xdai", 100], - ]; - for (const [name, networkId] of legacy) { - const network = Network.from(name); - assert.equal(network.name, name, name); - assert.equal(network.networkId, BigInt(networkId), name); + it("rejects the former Ethereum network profiles", () => { + for (const name of [ + "homestead", + "ropsten", + "rinkeby", + "goerli", + "kovan", + "sepolia", + "classic", + "classicKotti", + "xdai", + ]) { + assert.throws(() => Network.from(name), /unknown network/, name); } }); @@ -401,7 +396,6 @@ describe("network registry", () => { assert.equal(Network.from(3).name, "devin"); assert.equal(Network.from(1).name, "mainnet"); assert.equal(Network.from(10).name, "private"); - assert.equal(Network.from("homestead").name, "mainnet"); }); it("gives every Core network a valid address prefix", () => { diff --git a/src.ts/address/index.ts b/src.ts/address/index.ts index 2ed74316..091ef029 100644 --- a/src.ts/address/index.ts +++ b/src.ts/address/index.ts @@ -77,6 +77,11 @@ const precompiledAddresses = [ "00000000000000000000000000000000000000000009", ]; +/** The raw zero address and the precompiles are valid on every network. */ +function isSystemAddress(address: string): boolean { + return precompiledAddresses.includes(removeHexPrefix(address).toLowerCase()); +} + function removeHexPrefix(val: string): string { return val.substring(0, 2) === "0x" ? val.substring(2) : val; } @@ -228,7 +233,7 @@ function getAddress(address: string): string { // lower-case. Without normalizing, two spellings of one address compare // unequal. const raw = removeHexPrefix(address).toLowerCase(); - if (precompiledAddresses.includes(raw)) { + if (isSystemAddress(raw)) { return "0x" + raw; } @@ -379,6 +384,7 @@ export { getAddress, getIcapAddress, calculateCheckSum, + isSystemAddress, networkIdToPrefix, prefixToNetworkId, isNetworkPrefix, diff --git a/src.ts/providers/default-provider.ts b/src.ts/providers/default-provider.ts index e6cd053d..bbd513ed 100644 --- a/src.ts/providers/default-provider.ts +++ b/src.ts/providers/default-provider.ts @@ -1,21 +1,11 @@ -import { assert } from "../utils/index.js"; - -import { AnkrProvider } from "./provider-ankr.js"; -import { AlchemyProvider } from "./provider-alchemy.js"; -//import { BlockscoutProvider } from "./provider-blockscout.js"; -import { CloudflareProvider } from "./provider-cloudflare.js"; -import { InfuraProvider } from "./provider-infura.js"; -//import { PocketProvider } from "./provider-pocket.js"; -import { QuickNodeProvider } from "./provider-quicknode.js"; - -import { FallbackProvider } from "./provider-fallback.js"; -import { JsonRpcProvider } from "./provider-jsonrpc.js"; +import { assert, assertArgument } from "../utils/index.js"; import { Network } from "./network.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; import { WebSocketProvider } from "./provider-websocket.js"; import type { AbstractProvider } from "./abstract-provider.js"; import type { Networkish } from "./network.js"; -import { WebSocketLike } from "./provider-websocket.js"; +import type { WebSocketLike } from "./provider-websocket.js"; function isWebSocketLike(value: any): value is WebSocketLike { return ( @@ -25,211 +15,46 @@ function isWebSocketLike(value: any): value is WebSocketLike { ); } -const Testnets = - "goerli kovan sepolia classicKotti optimism-goerli arbitrum-goerli matic-mumbai bnbt".split( - " ", - ); - /** - * Returns a default provider for %%network%%. - * - * If %%network%% is a [[WebSocketLike]] or string that begins with - * ``"ws:"`` or ``"wss:"``, a [[WebSocketProvider]] is returned backed - * by that WebSocket or URL. - * - * If %%network%% is a string that begins with ``"HTTP:"`` or ``"HTTPS:"``, - * a [[JsonRpcProvider]] is returned connected to that URL. - * - * Otherwise, a default provider is created backed by well-known public - * Web3 backends (such as [[link-infura]]) using community-provided API - * keys. - * - * The %%options%% allows specifying custom API keys per backend (setting - * an API key to ``"-"`` will omit that provider) and ``options.exclusive`` - * can be set to either a backend name or and array of backend names, which - * will whitelist **only** those backends. - * - * Current backend strings supported are: - * - ``"alchemy"`` - * - ``"ankr"`` - * - ``"cloudflare"`` - * - ``"chainstack"`` - * - ``"etherscan"`` - * - ``"infura"`` - * - ``"publicPolygon"`` - * - ``"quicknode"`` - * - * @example: - * // Connect to a local Geth node - * provider = getDefaultProvider("http://localhost:8545/"); - * - * // Connect to Ethereum mainnet with any current and future - * // third-party services available - * provider = getDefaultProvider("mainnet"); - * - * // Connect to Polygon, but only allow Etherscan and - * // INFURA and use "MY_API_KEY" in calls to Etherscan. - * provider = getDefaultProvider("matic", { - * etherscan: "MY_API_KEY", - * exclusive: [ "etherscan", "infura" ] - * }); + * Connects to the public Core Mainnet (the default) or Devin RPC. + * The provider checks the node's network ID against the selected profile. + * Pass an HTTP(S) URL, WebSocket URL or WebSocket connection to use your own node. + * Named profiles each use a single endpoint and accept no backend options. */ export function getDefaultProvider( - network?: string | Networkish | WebSocketLike, + network?: Networkish | WebSocketLike, options?: any, ): AbstractProvider { - if (options == null) { - options = {}; - } - - const allowService = (name: string) => { - if (options[name] === "-") { - return false; - } - if (typeof options.exclusive === "string") { - return name === options.exclusive; - } - if (Array.isArray(options.exclusive)) { - return options.exclusive.indexOf(name) !== -1; - } - return true; - }; - - if (typeof network === "string" && network.match(/^https?:/)) { + if (typeof network === "string" && /^https?:/i.test(network)) { return new JsonRpcProvider(network); } - if ( - (typeof network === "string" && network.match(/^wss?:/)) || + (typeof network === "string" && /^wss?:/i.test(network)) || isWebSocketLike(network) ) { return new WebSocketProvider(network); } - // Get the network and name, if possible - let staticNetwork: null | Network = null; - try { - staticNetwork = Network.from(network); - } catch (error) {} - - const providers: Array = []; - - if (allowService("publicPolygon") && staticNetwork) { - if (staticNetwork.name === "matic") { - providers.push( - new JsonRpcProvider("https:/\/polygon-rpc.com/", staticNetwork, { - staticNetwork, - }), - ); - } else if (staticNetwork.name === "matic-amoy") { - providers.push( - new JsonRpcProvider( - "https:/\/rpc-amoy.polygon.technology/", - staticNetwork, - { staticNetwork }, - ), - ); - } - } - - if (allowService("alchemy")) { - try { - providers.push(new AlchemyProvider(network, options.alchemy)); - } catch (error) { - console.log(error); - } - } - - if (allowService("ankr") && options.ankr != null) { - try { - providers.push(new AnkrProvider(network, options.ankr)); - } catch (error) { - console.log(error); - } - } - /* Temporarily remove until custom error issue is fixed - if (allowService("blockscout")) { - try { - providers.push(new BlockscoutProvider(network, options.blockscout)); - } catch (error) { } - } -*/ - if (allowService("cloudflare")) { - try { - providers.push(new CloudflareProvider(network)); - } catch (error) { - console.log(error); - } - } + assertArgument( + options == null || Object.keys(options).length === 0, + "Core RPC profiles do not accept backend options", + "options", + "[ REDACTED ]", + ); - if (allowService("infura")) { - try { - let projectId = options.infura; - let projectSecret: undefined | string = undefined; - if (typeof projectId === "object") { - projectSecret = projectId.projectSecret; - projectId = projectId.projectId; - } - providers.push(new InfuraProvider(network, projectId, projectSecret)); - } catch (error) { - console.log(error); - } + const profile = Network.from(network); + if (profile.name === "mainnet" && profile.networkId === 1n) { + return new JsonRpcProvider("https://xcbapi.coreblockchain.net/", profile); } - /* - if (options.pocket !== "-") { - try { - let appId = options.pocket; - let secretKey: undefined | string = undefined; - let loadBalancer: undefined | boolean = undefined; - if (typeof(appId) === "object") { - loadBalancer = !!appId.loadBalancer; - secretKey = appId.secretKey; - appId = appId.appId; - } - providers.push(new PocketProvider(network, appId, secretKey, loadBalancer)); - } catch (error) { console.log(error); } - } -*/ - if (allowService("quicknode")) { - try { - let token = options.quicknode; - providers.push(new QuickNodeProvider(network, token)); - } catch (error) { - console.log(error); - } + if (profile.name === "devin" && profile.networkId === 3n) { + return new JsonRpcProvider("https://xcbapi.corecoin.cc/", profile); } - assert( - providers.length, - "unsupported default network", + false, + "no public Core RPC for this network; pass a node URL", "UNSUPPORTED_OPERATION", { operation: "getDefaultProvider", }, ); - - // No need for a FallbackProvider - if (providers.length === 1) { - return providers[0]; - } - - // We use the floor because public third-party providers can be unreliable, - // so a low number of providers with a large quorum will fail too often - let quorum = Math.floor(providers.length / 2); - if (quorum > 2) { - quorum = 2; - } - - // Testnets don't need as strong a security gaurantee and speed is - // more useful during testing - if (staticNetwork && Testnets.indexOf(staticNetwork.name) !== -1) { - quorum = 1; - } - - // Provided override qorum takes priority - if (options && options.quorum) { - quorum = options.quorum; - } - - return new FallbackProvider(providers, undefined, { quorum }); } diff --git a/src.ts/providers/format.ts b/src.ts/providers/format.ts index df0add86..09d268f4 100644 --- a/src.ts/providers/format.ts +++ b/src.ts/providers/format.ts @@ -243,8 +243,7 @@ export function formatTransactionResponse( { hash: formatHash, - // Some nodes do not return this, usually test nodes (like Ganache) - index: allowNull(getNumber, undefined), + index: allowNull(getNumber), type: (value: any) => { if (value === "0x" || value == null) { @@ -256,7 +255,6 @@ export function formatTransactionResponse( blockHash: allowNull(formatHash, null), blockNumber: allowNull(getNumber, null), - transactionIndex: allowNull(getNumber, null), from: getAddress, @@ -274,6 +272,7 @@ export function formatTransactionResponse( networkId: allowNull(getBigInt, null), }, { + index: ["transactionIndex"], data: ["input"], energyLimit: ["energy"], networkId: ["network_id"], diff --git a/src.ts/providers/formatting.ts b/src.ts/providers/formatting.ts index b3a5e195..7477006c 100644 --- a/src.ts/providers/formatting.ts +++ b/src.ts/providers/formatting.ts @@ -336,9 +336,9 @@ export interface TransactionResponseParams { hash: string; /** - * The transaction index. + * The zero-based position in the block, when the node reports it. */ - index: number; + index?: number | undefined; /** * The [[link-eip-2718]] transaction type. diff --git a/src.ts/providers/network.ts b/src.ts/providers/network.ts index e97bb83a..0e506ea7 100644 --- a/src.ts/providers/network.ts +++ b/src.ts/providers/network.ts @@ -298,7 +298,6 @@ type Options = { altNames?: Array; }; -// See: https://chainlist.org let injected = false; function injectCommonNetworks(): void { if (injected) { @@ -329,35 +328,7 @@ function injectCommonNetworks(): void { } } - // Core's own networks; these are the ones `networkIdToPrefix` can render - // an address for, and they own the numeric ids they share with any legacy - // name below. - registerCore("mainnet", 1, { altNames: ["homestead", "cb"] }); + registerCore("mainnet", 1, { altNames: ["cb"] }); registerCore("devin", 3, { altNames: ["testnet", "ab"] }); registerCore("private", 10, { altNames: ["ce"] }); - - // The names this registry shipped with. They have no Core address prefix - // so they cannot render an address, but resolving them by name used to - // work and code may still refer to them. Registered by name only: the - // numeric ids belong to the Core networks above, and Network.register - // refuses to overwrite an existing entry. - for (const [name, networkId] of [ - ["ropsten", 3], - ["rinkeby", 4], - ["goerli", 5], - ["kovan", 42], - ["sepolia", 11155111], - ["classic", 61], - ["classicKotti", 6], - ["xdai", 100], - ] as Array<[string, number]>) { - if (Networks.get(name)) { - continue; - } - Network.register(name, () => { - const network = new Network(name, networkId); - network.attachPlugin(new EnergyCostPlugin()); - return network; - }); - } } diff --git a/src.ts/providers/provider.ts b/src.ts/providers/provider.ts index 79373abb..cb95a70f 100644 --- a/src.ts/providers/provider.ts +++ b/src.ts/providers/provider.ts @@ -809,9 +809,10 @@ export class TransactionResponse readonly blockHash: null | string; /** - * The index within the block that this transaction resides at. + * The zero-based position in the block. This is undefined for pending + * transactions or when the node omits the index. */ - readonly index!: number; + readonly index: number | undefined; /** * The transaction hash. diff --git a/src.ts/utils/units.ts b/src.ts/utils/units.ts index 3085eea4..d438c871 100644 --- a/src.ts/utils/units.ts +++ b/src.ts/utils/units.ts @@ -19,7 +19,7 @@ * * @_subsection api/utils:Unit Conversion [about-units] */ -import { assertArgument } from "./errors.js"; +import { assert, assertArgument } from "./errors.js"; import { FixedNumber } from "./fixednumber.js"; import { getNumber } from "./maths.js"; @@ -72,74 +72,43 @@ export function formatUnits( }).toString(); } -/** - * Converts the //decimal string// %%value%% to a BigInt, assuming - * %%unit%% decimal places. The %%unit%% may the number of decimal places - * or the name of a unit. - */ - -export const scientificToDecimal = (num: string | number) => { - // @ts-ignore - var nsign = Math.sign(num); - //remove the sign - // @ts-ignore - num = Math.abs(num); - //if the number is in scientific notation remove it - // @ts-ignore - if (/\d+\.?\d*e[\+\-]*\d+/i.test(num)) { - var zero = "0", - // @ts-ignore - parts = String(num).toLowerCase().split("e"), //split into coeff and exponent - e = parts.pop(), //store the exponential part - // @ts-ignore - l = Math.abs(e), //get the number of zeros - // @ts-ignore - sign = e / l, - coeff_array = parts[0].split("."); - if (sign === -1) { - l = l - coeff_array[0].length; - if (l < 0) { - // @ts-ignore - num = - coeff_array[0].slice(0, l) + - "." + - coeff_array[0].slice(l) + - (coeff_array.length === 2 ? coeff_array[1] : ""); - } else { - // @ts-ignore - num = zero + "." + new Array(l + 1).join(zero) + coeff_array.join(""); - } - } else { - var dec = coeff_array[1]; - if (dec) l = l - dec.length; - if (l < 0) { - // @ts-ignore - num = coeff_array[0] + dec.slice(0, l) + "." + dec.slice(l); - } else { - // @ts-ignore - num = coeff_array.join("") + new Array(l + 1).join(zero); - } - } - } - // @ts-ignore - return nsign < 0 ? "-" + num : num; -}; -export const trimDecimals = (n: string, decimals = 18) => { - n += ""; - - if (n.indexOf(".") === -1) return n; - - const arr = n.split("."); - // Rebuilding from the first two parts alone would quietly turn a - // malformed amount like "1.2.3" into "1.2", so leave anything that is not - // a single decimal point untouched and let the parser reject it. - if (arr.length !== 2) { - return n; - } - const fraction = arr[1].substring(0, decimals); - return fraction.length ? arr[0] + "." + fraction : arr[0]; -}; +// Shift the decimal point using only string digits. The exponent controls +// a position, never the numeric value of the significand. +export function scientificToDecimal(num: string | number): string { + const value = String(num); + if (!/[eE]/.test(value)) return value; + const match = /^([+-]?)([0-9]*)(?:\.([0-9]*))?[eE]([+-]?[0-9]+)$/.exec(value); + assertArgument( + match && (match[2] || match[3]), + "invalid FixedNumber string value", + "value", + value, + ); + const [, inputSign, whole, fraction = "", exponent] = match; + const sign = inputSign === "-" ? "-" : ""; + const digits = whole + fraction; + if (!/[1-9]/.test(digits)) return "0"; + const point = whole.length + Number(exponent); + + // No supported FixedNumber has over 80 decimal places or more than + // 155 integer digits (512 bits). Bound padding before allocating it. + assert(point > -80, "too many decimals for format", "NUMERIC_FAULT", { + operation: "parseUnits", + fault: "underflow", + value, + }); + assert(point <= digits.length + 155, "overflow", "NUMERIC_FAULT", { + operation: "parseUnits", + fault: "overflow", + value, + }); + if (point <= 0) return sign + "0." + "0".repeat(-point) + digits; + if (point >= digits.length) + return sign + digits + "0".repeat(point - digits.length); + return sign + digits.slice(0, point) + "." + digits.slice(point); +} +/** Parse decimal or scientific notation exactly in the requested unit. */ export function parseUnits(value: string, unit?: string | Numeric): bigint { assertArgument( typeof value === "string", @@ -147,21 +116,19 @@ export function parseUnits(value: string, unit?: string | Numeric): bigint { "value", value, ); - if (value.includes("e")) { - value = scientificToDecimal(value).toString(); - } let decimals = 18; if (typeof unit === "string") { const index = names.indexOf(unit); assertArgument(index >= 0, "invalid unit", "unit", unit); decimals = 3 * index; - value = trimDecimals(value, decimals); } else if (unit != null) { decimals = getNumber(unit, "unit"); - value = trimDecimals(value, decimals); } - return FixedNumber.fromString(value, { decimals, width: 512 }).value; + return FixedNumber.fromString(scientificToDecimal(value), { + decimals, + width: 512, + }).value; } /** diff --git a/src.ts/wallet/base-wallet.ts b/src.ts/wallet/base-wallet.ts index 6603aa22..bedd5dbb 100644 --- a/src.ts/wallet/base-wallet.ts +++ b/src.ts/wallet/base-wallet.ts @@ -1,4 +1,8 @@ -import { getAddress } from "../address/index.js"; +import { + getAddress, + isSystemAddress, + networkIdToPrefix, +} from "../address/index.js"; import { resolveAddress } from "../address/checks.js"; import { hashMessage, TypedDataEncoder } from "../hash/index.js"; import { AbstractSigner, copyRequest } from "../providers/index.js"; @@ -123,6 +127,21 @@ export class BaseWallet extends AbstractSigner { // Build the transaction const btx = Transaction.from(>tx); + const prefix = networkIdToPrefix(Number(btx.networkId)); + assertArgument( + this.address.substring(2, 4) === prefix, + "transaction network does not match wallet address", + "tx.networkId", + btx.networkId, + ); + if (btx.to != null && !isSystemAddress(btx.to)) { + assertArgument( + btx.to.substring(2, 4) === prefix, + "recipient address does not match transaction network", + "tx.to", + btx.to, + ); + } const unSignedSerialized = btx.unsignedSerialized; const unsignedHash = sha256(unSignedSerialized); // sha256(btx.unsignedSerialized) diff --git a/src.ts/wallet/hdwallet.ts b/src.ts/wallet/hdwallet.ts index f09ea22f..235a16a3 100644 --- a/src.ts/wallet/hdwallet.ts +++ b/src.ts/wallet/hdwallet.ts @@ -7,7 +7,6 @@ import { randomBytes, ripemd160, SigningKey, sha256 } from "../crypto/index.js"; import { dataSlice, defineProperties, - getBytes, getNumber, hexlify, assertPrivate, @@ -71,32 +70,32 @@ const LegacyPathPrefix = "m/44'/60'/0'/0"; * buffer, and every such seed derives the same key. Validating here keeps * unrelated seeds from colliding on one wallet. */ -function seedToHex(seed: string | BytesLike): string { - let hex: string; - - if (typeof seed === "string") { - hex = /^0x/i.test(seed) ? seed.substring(2) : seed; +function seedToHex(seed: BytesLike): string { + const value = typeof seed === "string" ? seed.replace(/^0x/i, "") : seed; + assertArgument( + typeof value === "string" || value instanceof Uint8Array, + "seed must be hex or bytes", + "seed", + "[ REDACTED ]", + ); + if (typeof value === "string") { assertArgument( - /^[0-9a-f]*$/i.test(hex) && hex.length % 2 === 0, + !/[^0-9a-f]/i.test(value) && value.length % 2 === 0, "seed must be a hex string", "seed", - seed, + "[ REDACTED ]", ); - } else { - // Byte input is accepted too; the derivation copied such a seed - // verbatim before this check existed. - hex = hexlify(getBytes(seed, "seed")).substring(2); } - - // BIP-32 permits a seed of 16 to 64 bytes. + const size = typeof value === "string" ? value.length / 2 : value.length; assertArgument( - hex.length >= 32 && hex.length <= 128, + size >= 16 && size <= 64, "seed must be between 16 and 64 bytes", "seed", - seed, + "[ REDACTED ]", ); - - return hex.toLowerCase(); + return typeof value === "string" + ? value.toLowerCase() + : hexlify(value).substring(2); } // "Bitcoin seed" @@ -405,7 +404,7 @@ export class HDNodeWallet extends BaseWallet { mnemonic, prefix, }: { - _seed: string; + _seed: BytesLike; mnemonic: null | Mnemonic; prefix: string; }): HDNodeWallet { @@ -519,7 +518,7 @@ export class HDNodeWallet extends BaseWallet { prefix, path, }: { - seed: string; + seed: BytesLike; prefix: string; path?: string; }): HDNodeWallet { diff --git a/src.ts/wallet/mnemonicToSeed.ts b/src.ts/wallet/mnemonicToSeed.ts index 1d91027d..9c7ae0e9 100644 --- a/src.ts/wallet/mnemonicToSeed.ts +++ b/src.ts/wallet/mnemonicToSeed.ts @@ -1,39 +1,13 @@ import { Buffer } from "buffer"; import { pbkdf2Sync } from "../crypto/crypto.js"; -import utf8 from "utf8"; -export function mnemonicToSeed(mnemonic: string, password?: string): string { - if (!password) { - password = ""; - } - const t = generateSeed(mnemonic, password); - return t.goldilock; -} - -const generateSeed = (mnemonic: string, password?: string) => { - const goldilockSaltPrefix = "mnemonic"; - const aesSaltPrefix = "mnemonicfortheAESkey"; - - const goldilockSalt = utf8.encode(goldilockSaltPrefix + password); - const aesSalt = utf8.encode(aesSaltPrefix + password); - const goldilockKey = pbkdf2Sync( - Buffer.from(mnemonic), - Buffer.from(goldilockSalt), - 2048, - 64, - "sha512", +export function mnemonicToSeed(mnemonic: string, password?: string): string { + const words = Buffer.from(mnemonic.normalize("NFKD"), "utf8"); + const salt = Buffer.from( + ("mnemonic" + (password ?? "")).normalize("NFKD"), + "utf8", ); - - const aesKeySeed = pbkdf2Sync( - Buffer.from(mnemonic), - Buffer.from(aesSalt), - 2048, - 64, - "sha512", + return Buffer.from(pbkdf2Sync(words, salt, 2048, 64, "sha512")).toString( + "hex", ); - - return { - aes: Buffer.from(aesKeySeed).toString("hex"), - goldilock: Buffer.from(goldilockKey).toString("hex"), - }; -}; +} diff --git a/src.ts/wallet/wallet.ts b/src.ts/wallet/wallet.ts index c9f0a650..51cccb65 100644 --- a/src.ts/wallet/wallet.ts +++ b/src.ts/wallet/wallet.ts @@ -19,6 +19,7 @@ import { Mnemonic } from "./mnemonic.js"; import type { ProgressCallback } from "../crypto/index.js"; import type { Provider } from "../providers/index.js"; +import type { BytesLike } from "../utils/index.js"; import type { CrowdsaleAccount } from "./json-crowdsale.js"; import type { KeystoreAccount } from "./json-keystore.js"; @@ -271,7 +272,7 @@ export class Wallet extends BaseWallet { provider, path, }: { - seed: string; + seed: BytesLike; prefix: string; path?: string; provider?: Provider; diff --git a/testcases/golden-vectors.json b/testcases/golden-vectors.json index 8fa672c3..42b9a4ca 100644 --- a/testcases/golden-vectors.json +++ b/testcases/golden-vectors.json @@ -348,10 +348,10 @@ }, "signed": { "from": "0xcb23f5e89ba978317da861b7ad06ba3103d41c876098", - "hash": "0x0bdc4e7283fd57896ec8cf94bfb62458b74d149bfce2491a7610b6f102952ec6", + "hash": "0x3bf41242844c7f4c5c848826f216ceb0e491f83e02b78089c7f41c0abe3437df", "nonce": 3, - "serialized": "0xf8d803843b9aca008252080196ab41f5e89ba978317da861b7ad06ba3103d41c876098880de0b6b3a764000080b8ab44de4e64bb951da075c85760a299331b8a74a6db30ebbfb1a4b286fa74378dd7e4b0691030d13769846bbda1513dc8030206a77c09e06ede009c9335e82ba20767363963deaec613e2979c95b5215763a1b96fca4e90f16fb4a738d5f64b68659a9b97fe7e716a5c082fd0a1d9d1661c3100e0758a33267939a394fb5ccb202ee851cebc2e89c91ac1289e2bfcddfd9ff9fc5694b0f569d7f7e9da16e1cde9301b29f48128b3cbd1168580", - "to": "0xab41f5e89ba978317da861b7ad06ba3103d41c876098" + "serialized": "0xf8d803843b9aca008252080196cb23f5e89ba978317da861b7ad06ba3103d41c876098880de0b6b3a764000080b8ab8b05d99c1d4db8a2dbea27109bab36467edb4ed5b9e50e200fee6c206388e08db3a2465305241a82b6415e47265a70de9312d69666bfaaf400aeb99be223c71e93fd2d11fc7a8e6ed3eb093115f6ef436cf335f9f5df3b72587933fc7ff8a47698f809ba85ebd971ccdbe97ed4f4b4360f00e0758a33267939a394fb5ccb202ee851cebc2e89c91ac1289e2bfcddfd9ff9fc5694b0f569d7f7e9da16e1cde9301b29f48128b3cbd1168580", + "to": "0xcb23f5e89ba978317da861b7ad06ba3103d41c876098" }, "withData": "0xef03843b9aca0082520896ab41f5e89ba978317da861b7ad06ba3103d41c876098880de0b6b3a764000084deadbeef01", "noTo": "0xd503843b9aca0082520880880de0b6b3a76400008001"