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

Error: Number can only safely store up to 53 bits #114

Closed
aakilfernandes opened this issue Dec 29, 2016 · 27 comments
Closed

Error: Number can only safely store up to 53 bits #114

aakilfernandes opened this issue Dec 29, 2016 · 27 comments

Comments

@aakilfernandes
Copy link
Contributor

Getting this while running the tests on a fresh clone.

OSX Yosemite
Node v6.3.0

# [bcInvalidRLPTest] BLOCK_gasLimit_TooLarge
ok 186 correct pre stateRoot
/Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/bn.js/lib/bn.js:6
    if (!val) throw new Error(msg || 'Assertion failed');
              ^

Error: Number can only safely store up to 53 bits
    at assert (/Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/bn.js/lib/bn.js:6:21)
    at BN.toNumber (/Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/bn.js/lib/bn.js:506:7)
    at Object.exports.bufferToInt (/Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/ethereumjs-block/node_modules/ethereumjs-util/index.js:199:40)
    at BlockHeader.validateGasLimit (/Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/ethereumjs-block/header.js:146:26)
    at /Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/ethereumjs-block/header.js:196:15
    at /Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/ethereumjs-blockchain/index.js:326:7
    at /Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/levelup/lib/levelup.js:230:7
    at Immediate.callNext (/Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/memdown/memdown.js:173:5)
    at runCallback (timers.js:566:20)
    at tryOnImmediate (timers.js:546:5)
npm ERR! Test failed.  See above for more details.
@DevNebulae
Copy link

Getting the same error with no clue on how to fix it. Does anybody have a fix for this or an explanation as to why this happens?

@assafmo
Copy link

assafmo commented Jun 29, 2017

This happened to me when I tried to index string type in an event.
https://ethereum.stackexchange.com/a/7170/12112

@DevNebulae
Copy link

I actually figured it out and it is REALLY stupid... It occurred to me when I actually used a value for the gas field which is greater than 53 bits. I actually set it to half an Ether and that works out to be greater than 53 bits...

@axic
Copy link
Member

axic commented Dec 9, 2017

This actually seems to be a bug in ethereumjs-block.

@hugo-dc
Copy link
Contributor

hugo-dc commented Dec 15, 2017

@axic recently I submitted a new PR to the tests repository, the tests I submitted is related to this problem.

ethereum/tests#381

I think this is something that the bn.js library validates, here is an example of the validation in the iaddn function

https://github.com/indutny/bn.js/blob/master/lib/bn.js#L2145

@axic
Copy link
Member

axic commented Dec 17, 2017

This seems to be a problem in ethereumjs-block and that the block gas limit is higher than 53bits:

Error: Number can only safely store up to 53 bits
    at assert (/Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/bn.js/lib/bn.js:6:21)
    at BN.toNumber (/Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/bn.js/lib/bn.js:506:7)
    at Object.exports.bufferToInt (/Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/ethereumjs-block/node_modules/ethereumjs-util/index.js:199:40)
    at BlockHeader.validateGasLimit (/Users/aakilfernandes/projects/safemarket/ethereumjs-vm/node_modules/ethereumjs-block/header.js:146:26)

@riordant
Copy link

having the same problem where gasLimit in testrpc is set greater than 9007199254740991 (2^53 -1) and tests are ran.

@greggootz
Copy link

Make sure your {gas: xxxx} is a round number.

Bad: {gas: 40000.0000001}
Good: {gas: 40000}

Math.floor() to the rescue.

Example of usage:

const estGas = Math.floor(await instance.myMethod.estimateGas({ from: wallet })

Good luck!

@shrugs
Copy link

shrugs commented Apr 8, 2018

(sorry for the notification, but this is for future searchers)

I got this issue when I attempted to issue a evm_increaseTime call against ganache while using a duration argument that was stupidly large. It was hard to track down because I was accidentally using a BigNumber in a traditional 30 + myBigNumber way.

@nneverlander
Copy link

@assafmo solution worked for me. Just don't index strings in your events

@liamzebedee
Copy link

Just encountered this. Not relevant exactly the JS VM, but for any other souls that come here, an addition to what @DevNebulae said:

I had set the gasLimit with ganache-cli to a number bigger than 53 bits. Changed it, still didn't work. Turns out that Metamask caches the gas limit, so you have to switch between networks and switch back before it gets the new one. Until then, you'll get a 53 bits error on any transaction.

@nikita-fuchs
Copy link

My gaslimit is 800000 and I still get this error. Here is the code that causes it:

BN.js:498

BN.prototype.toNumber = function toNumber () {
    var ret = this.words[0];
    if (this.length === 2) {
      ret += this.words[1] * 0x4000000;
    } else if (this.length === 3 && this.words[2] === 0x01) {
      // NOTE: at this stage it is known that the top bit is set
      ret += 0x10000000000000 + (this.words[1] * 0x4000000);
    } else if (this.length > 2) {
      assert(false, 'Number can only safely store up to 53 bits');
    }
    return (this.negative !== 0) ? -ret : ret;
  };

Does anyone have a clue what he is parsing here?

@holgerd77
Copy link
Member

@nikita-fuchs You should be able to debug this by directly injecting some log statements in this file in your node_modules folder?

@nikita-fuchs
Copy link

nikita-fuchs commented Nov 5, 2018 via email

@XBITSwitzerland
Copy link

Hello, I just ran into the same error. But with the quorum tutorial from truffle. Here is my stack overflow post for further description: https://stackoverflow.com/questions/54128954/quorum-ethereum-truffle-error-number-can-only-safely-store-up-to-53-bits/54182896#54182896

@orlein
Copy link

orlein commented Jan 18, 2019

Hello, I'm facing the same issue.

You can just get web3's util to variable. for example,

var BigNumber = web3.utils.BN;
var amount = new BigNumber(3700 * 10 ** 3);

and amount is BigNumber. so you can compare to any Ethereum uint256 like this:

return Token.deployed().then((instance) => {
    token = instance;
    return token .balanceOf.call(account_one);
}).then((balance) => {
    account_one_starting_balance = balance;
    return token.balanceOf.call(account_two);
}).then((balance) => {
    account_two_starting_balance = balance;
    return token.transfer(account_two, amount, {from: account_one});
}).then(() => {
    return token.balanceOf.call(account_one)
}).then((balance) => {
    account_one_ending_balance = balance;
    return token.balanceOf.call(account_two);
}).then((balance) => {
    account_two_ending_balance = balance;
    assert.equal(account_one_ending_balance.toString(), account_one_starting_balance.sub(amount).toString(), "Amount wasn't correctly taken from the sender");
    assert.equal(account_two_ending_balance.toString(), account_two_starting_balance.add(amount).toString(), "Amount wasn't correctly sent to the receiver");
});

This code is from truffle's contract test code to test if the transfer is working with account_one to account_to.

@holgerd77
Copy link
Member

There are actually few issues which make me so confused within the whole EthereumJS org like this one. Open since 2016, with new reports coming in several times, all citing very much different code parts.

Is this still a thing? How much is this related to the VM implementation? Does anyone have some code part which can directly be executed on the VM and is triggering the respective error?

@ghost
Copy link

ghost commented May 21, 2019

In many blogs I've found it was a Truffle version problem. Truffle v5 would make problems of this type. They suggest to downgrade to truffle@4.1.15.

This has not been so for me. I have continue to use truffle v5. I've resolved by checking my gas limit when I sent a transaction.
gasLimit: web3.utils.toHex( gas_limit ),//The maximum gas provided for this transaction (gas limit)

Node: v8.11.4
Truffle: 5.0.12
Web3: 1.0.0-beta.52
Truffle-contract: 4.0.11
Truffle-interface-adapter@0.1.2
│ └── web3@1.0.0-beta.37
└── web3@1.0.0-beta.37
Ganache-cli: v6.4.3 (ganache-core: 2.5.5)
Ethereumjs-tx: 1.3.4

@alcuadrado
Copy link
Member

Can you give us more info about your failing setup @macman18? Truffle version? Node version? Are you using ganache? Which version? Thanks!

@ghost
Copy link

ghost commented May 21, 2019

Can you give us more info about your failing setup @macman18? Truffle version? Node version? Are you using ganache? Which version? Thanks!

Of course. I've also added a new discovered... Now it is definitive!

@alcuadrado
Copy link
Member

alcuadrado commented May 21, 2019

This has not been so for me. I have continue to use truffle v5. I've resolved by checking my gas limit when I sent a transaction.
gasLimit: web3.utils.toHex( gas_limit ),//The maximum gas provided for this transaction (gas limit)

So the problem appeared when sending a tx without an explicit gas limit? What is the value of gas_limit? Can you paste the entire statement that sends that tx?

Also, your truffle config would be useful.

@ghost
Copy link

ghost commented May 21, 2019

So the problem appeared when sending a tx without an explicit gas limit? What is the value of gas_limit? Can you paste the entire statement that sends that tx?
In my case, also, I had to control whether transaction gas were less or equal of the ganache gas limit. You have to check it because could be different and the transaction one could be higher.


My versions:

Node: v8.11.4
Truffle: 5.0.12
Web3: 1.0.0-beta.52
Truffle-contract: 4.0.11
Truffle-interface-adapter@0.1.2
│ └── web3@1.0.0-beta.37
└── web3@1.0.0-beta.37
Ganache-cli: v6.4.3 (ganache-core: 2.5.5)
Ethereumjs-tx: 1.3.4


Also, your truffle config would be useful.

Truffle-config.js

networks: { development: { host: "127.0.0.1", // Localhost (default: none) port: 8545, // Standard Ethereum port (default: none) network_id: "*", // Any network (default: none) } }, mocha: { // timeout: 100000 }, // Configure your compilers compilers: { solc: { version: "0.5.7" // Fetch exact version from solc-bin (default: truffle's version) }//solc } }


Code of my send signed transaction function


`
async function sendSignedTransaction( param1, param2 ) {
const contractFunction = myContract.methods.MyMethodName( param1, param2 );
//Decoding
const functionAbi = contractFunction.encodeABI();
var estimatedGas;
var nonce;
try {
console.log("Getting gas estimate");
var gasAmount = await contractFunction.estimateGas( {from: myAccountAddress} );
estimatedGas = gasAmount.toString(16);
console.log("Estimated gas: " + estimatedGas);
} catch( e ) {
console.log( '=========== EXCEPTION IN METHOD ' + 'sendSignedTransaction, when calling: ' + 'estimateGas');
//console.log( e );
console.log( e.message );
}
try {
console.log( '\tGetting current tx nonce');
var _nonce = await web3.eth.getTransactionCount( myAccountAddress );
nonce = _nonce.toString(16);
console.log("Nonce: " + nonce);
var txParams = {
from: myAccountAddress,
to: contractAddress,
nonce: '0x' + nonce,
gasPrice: web3.utils.toHex(web3.utils.toWei('3', 'gwei')),
gasLimit: web3.utils.toHex( gas_limit ),//The maximum gas provided for this transaction (gas limit)
data: functionAbi,
value: 0
};
} catch( e ) {
console.log( '=========== EXCEPTION IN METHOD ' + 'sendSignedTransaction, when calling: ' + 'getTransactionCount');
//console.log( e );
console.log( e.message );
}
const tx = new Tx( txParams );
tx.sign( privateKey );
const serializedTx = tx.serialize();
console.log(serializedTx.toString('hex'));
var rawTx = '0x' + serializedTx.toString('hex');
console.log( '======================================================================' );
console.log("Send Signed Transaction");
console.log( '======================================================================' );
//Funziona anche così
web3.eth.sendSignedTransaction( rawTx )
.on('transactionHash', hash => {
console.log( '======================================================================' );
console.log('========== ON TRANSACTION HASH ============');
console.log('Tx Hash: '+ hash);
console.log('Get Receipt from Hash');
//web3.eth.getTransactionReceipt( hash ).then( console.log );
try{
const receipt = await web3.eth.getTransactionReceipt( hash );
console.log("Receipt:\n");
for(e in receipt )
console.log( e + ': ' + receipt[e] );
}catch(e) {
console.log(e);
}
})
.on('receipt', receipt => {
console.log( '======================================================================' );
console.log('========== ON RECEIPT ============');
console.log("Receipt:\n");
for(e in receipt )
console.log( e + ': ' + receipt[e] );
}).on('confirmation', (confirmationNumber, receipt) => {
console.log( '======================================================================' );
console.log( '========== ON CONFIRMATION =======');
console.log( '\t confirmationNumber: ' + confirmationNumber );
console.log("Receipt:\n");
for(e in receipt )
console.log( e + ': ' + receipt[e] );

    console.log( '======================================================================' );
})
.on('error', e => {
    console.log("======================== ERROR ON SEND RAW TRANSACTION ==============================");
    errorOnSendSignedTransactionHandler( e )
});

`

@Chococoin
Copy link

My Versions:

Truffle v5.0.22,
Node v10.15.2,
Ganache CLI v6.4.4 (ganache-core: 2.5.6)

a portion of my code:

219.-  it('Receiving properly a bid', async () => {
220.-      var newBid = 5 * Math.pow(10, 18);
221.-      bid = await chocoAuction.bid({ from: accounts[1], value: newBid });
222.-      highestBid = await chocoAuction.highestBid.call({ from: accounts[2] });
*223.-      var hiBid = highestBid.toNumber();
224.-      console.log(bid);
225.-      assert(bid);
 	  ;})

The Error after $> truffle test:

'Receiving properly a bid:' Error: Number can only safely store up to 53 bits at assert (C:\Users\Choco\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\bn.js\lib\bn.js:6:1) at BN.toNumber (C:\Users\Choco\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\bn.js\lib\bn.js:506:1) at Context.it (test\chocoAuction.js:223:28) at process._tickCallback (internal/process/next_tick.js:68:7)

@trongdth
Copy link

trongdth commented Oct 6, 2020

I can able to run truffle test by using toString() method. Here is an example of getting token balance

const o = {
	balance: 2000000000 * (10 ** 18),
}

let owner_balance = await tokoin.balanceOf(root, {
	from: root
});

eq(o.balance, owner_balance.toString());

holgerd77 added a commit that referenced this issue Dec 1, 2020
holgerd77 pushed a commit that referenced this issue Dec 14, 2020
holgerd77 pushed a commit that referenced this issue Mar 11, 2021
Added babel-cli to distribute ES5 version on npm
@holgerd77
Copy link
Member

This hasn't been reported for quite some time, will close.

@holgerd77
Copy link
Member

(feel free to reopen though)

@holgerd77
Copy link
Member

On the various libraries, input is now directly taken as a Buffer or a BN.js object - at least for the values allowing for a bigger number input. And internally number conversion is generally avoided. So it is generally very likely that this shouldn't be an issue any more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests