0

I came accross this function to mint token for a crowdsale but I don't understand the meaning of the bit shift operations and what bit array should represent.. what is this code doing ? The code can be found here: https://github.com/bokkypoobah/ZeroSumCrowdsaleContractAudit/blob/9fe4765a0a0394a476a618608a4914754651ce59/contracts/Ledger.sol#L290

The function is this one:

function multiMint(uint nonce, uint256[] bits) onlyOwner {
    require(!mintingStopped);
    if (nonce != mintingNonce) return;
    mintingNonce += 1;
    uint256 lomask = (1 << 96) - 1;
    uint created = 0;
    for (uint i=0; i<bits.length; i++) {
        address a = address(bits[i]>>96);
        uint value = bits[i]&lomask;
        balanceOf[a] = balanceOf[a] + value;
        controller.ledgerTransfer(0, a, value);
        created += value;
    }
    totalSupply += created;
}
1

The author is trying to save resources (mostly the gas used to transmit the data to the contract within the transaction) by packing both the address and the value within a single 256-bit word. Normally they would each occupy separate 256 bit words, so this technique saves about half the space/gas.

In hex (64 chars for 32 bytes, 256 bits) the packed uint256 input bits[i] looks like this:

0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF
<----- Ethereum address, 160 bits -----><--- Value, 96 bits --->

Two operations then extract the address a and the uint value:

address(bits[i]>>96) gets you the address by right shifting everything (zeros are inserted on the left):

0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF
                        <----- Ethereum address, 160 bits ----->

bits[i]&lomask gets you the value, since lomask is 96x1 bits, so the higher address bits are masked out by the & operation:

0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF
<----- Ethereum address, 160 bits -----><--- Value, 96 bits --->
<---   lomask 0 bits                ---><--- lomask 1 bits  --->

This doesn't conform to the Ethereum ABI, but that's not a big deal if the gains are worth it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.