# All files / web3-utils/src soliditySha3.js

88.6% Statements 101/114
85.34% Branches 99/116
100% Functions 8/8
88.6% Lines 101/114

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236

    2x
    2x
    2x

    2x
    120x
    2x
    118x
    1x
    117x
    2x
    115x
    2x
    113x

    113x

    113x

    113x

    113x

    2x
    78x
    78x

    2x
    19x
    19x

    2x
    60x
    60x
    21x
    13x

    8x

    39x
    8x
    31x

    31x
    31x

    2x

    120x

    120x

    17x
    1x

    16x
    103x
    4x
    99x
    12x
    87x
    9x
    7x

    2x

    9x
    2x

    7x

    78x

    78x

    18x

    18x
    6x

    18x
    1x

    17x
    60x

    37x

    37x
    37x

    37x

    37x
    23x

    23x

    23x
    23x

    23x
    15x

    8x

    2x
    107x
    1x

    106x

    106x
    80x
    80x

    26x
    26x

    26x
    13x

    106x
    26x

    106x
    19x
    19x
    2x

    17x

    104x
    17x
    33x

    16x

    87x
    84x

    2x
    85x

    85x

    78x

    2x
     /*
     This file is part of web3.js.

     web3.js is free software: you can redistribute it and/or modify
     it under the terms of the GNU Lesser General Public License as published by
     the Free Software Foundation, either version 3 of the License, or
     (at your option) any later version.

     web3.js is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU Lesser General Public License for more details.

     You should have received a copy of the GNU Lesser General Public License
     along with web3.js.  If not, see <http://www.gnu.org/licenses/>.
     */
    /**
     * @file soliditySha3.js
     * @author Fabian Vogelsteller <fabian@ethereum.org>
     * @date 2017
     */

    var _ = require('underscore');
    var BN = require('bn.js');
    var utils = require('./utils.js');

    var _elementaryName = function (name) {
        if (name.startsWith('int[')) {
            return 'int256' + name.slice(3);
        } else if (name === 'int') {
            return 'int256';
        } else if (name.startsWith('uint[')) {
            return 'uint256' + name.slice(4);
        } else if (name === 'uint') {
            return 'uint256';
        } else Iif (name.startsWith('fixed[')) {
            return 'fixed128x128' + name.slice(5);
        } else Iif (name === 'fixed') {
            return 'fixed128x128';
        } else Iif (name.startsWith('ufixed[')) {
            return 'ufixed128x128' + name.slice(6);
        } else Iif (name === 'ufixed') {
            return 'ufixed128x128';
        }
        return name;
    };

    // Parse N from type<N>
    var _parseTypeN = function (type) {
        var typesize = /^\D+(\d+).*$/.exec(type);
        return typesize ? parseInt(typesize[1], 10) : null;
    };

    // Parse N from type[<N>]
    var _parseTypeNArray = function (type) {
        var arraySize = /^\D+\d*\[(\d+)\]$/.exec(type);
        return arraySize ? parseInt(arraySize[1], 10) : null;
    };

    var _parseNumber = function (arg) {
        var type = typeof arg;
        if (type === 'string') {
            if (utils.isHexStrict(arg)) {
                return new BN(arg.replace(/0x/i,''), 16);
            } else {
                return new BN(arg, 10);
            }
        } else if (type === 'number') {
            return new BN(arg);
        } else Iif (utils.isBigNumber(arg)) {
            return new BN(arg.toString(10));
        } else Eif (utils.isBN(arg)) {
            return arg;
        } else {
            throw new Error(arg +' is not a number');
        }
    };

    /* eslint-disable complexity */
    var _solidityPack = function (type, value, arraySize) {
        var size, num;
        type = _elementaryName(type);

        if (type === 'bytes') {

            if (value.replace(/^0x/i,'').length % 2 !== 0) {
                throw new Error('Invalid bytes characters '+ value.length);
            }

            return value;
        } else if (type === 'string') {
            return utils.utf8ToHex(value);
        } else if (type === 'bool') {
            return value ? '01' : '00';
        } else if (type.startsWith('address')) {
            if(arraySize) {
                size = 64;
            } else {
                size = 40;
            }

            if(!utils.isAddress(value)) {
                throw new Error(value +' is not a valid address, or the checksum is invalid.');
            }

            return utils.leftPad(value.toLowerCase(), size);
        }

        size = _parseTypeN(type);

        if (type.startsWith('bytes')) {

            Iif(!size) {
                throw new Error('bytes[] not yet supported in solidity');
            }

            // must be 32 byte slices when in an array
            if(arraySize) {
                size = 32;
            }

            if (size < 1 || size > 32 || size < value.replace(/^0x/i,'').length / 2 ) {
                throw new Error('Invalid bytes' + size +' for '+ value);
            }

            return utils.rightPad(value, size * 2);
        } else if (type.startsWith('uint')) {

            Iif ((size % 8) || (size < 8) || (size > 256)) {
                throw new Error('Invalid uint'+size+' size');
            }

            num = _parseNumber(value);
            Iif (num.bitLength() > size) {
                throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength());
            }

            Iif(num.lt(new BN(0))) {
                throw new Error('Supplied uint '+ num.toString() +' is negative');
            }

            return size ? utils.leftPad(num.toString('hex'), size/8 * 2) : num;
        } else Eif (type.startsWith('int')) {

            Iif ((size % 8) || (size < 8) || (size > 256)) {
                throw new Error('Invalid int'+size+' size');
            }

            num = _parseNumber(value);
            Iif (num.bitLength() > size) {
                throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength());
            }

            if(num.lt(new BN(0))) {
                return num.toTwos(size).toString('hex');
            } else {
                return size ? utils.leftPad(num.toString('hex'), size/8 * 2) : num;
            }

        } else {
            // FIXME: support all other types
            throw new Error('Unsupported or invalid type: ' + type);
        }
    };
    /* eslint-enable complexity */

    /* eslint-disable complexity */
    var _processSoliditySha3Args = function (arg) {
        if(_.isArray(arg)) {
            throw new Error('Autodetection of array types is not supported.');
        }

        var type, value = '';
        var hexArg, arraySize;

        // if type is given
        if (_.isObject(arg) && (arg.hasOwnProperty('v') || arg.hasOwnProperty('t') || arg.hasOwnProperty('value') || arg.hasOwnProperty('type'))) {
            type = arg.t || arg.type;
            value = arg.v || arg.value;

        // otherwise try to guess the type
        } else {

            type = utils.toHex(arg, true);
            value = utils.toHex(arg);

            if (!type.startsWith('int') && !type.startsWith('uint')) {
                type = 'bytes';
            }
        }

        if ((type.startsWith('int') || type.startsWith('uint')) &&  typeof value === 'string' && !/^(-)?0x/i.test(value)) {
            value = new BN(value);
        }

        // get the array size
        if(_.isArray(value)) {
            arraySize = _parseTypeNArray(type);
            if(arraySize && value.length !== arraySize) {
                throw new Error(type +' is not matching the given array '+ JSON.stringify(value));
            } else {
                arraySize = value.length;
            }
        }

        if (_.isArray(value)) {
            hexArg = value.map(function (val) {
                return _solidityPack(type, val, arraySize).toString('hex').replace('0x','');
            });
            return hexArg.join('');
        } else {
            hexArg = _solidityPack(type, value, arraySize);
            return hexArg.toString('hex').replace('0x','');
        }
    };
    /* eslint-enable complexity */

    /**
     * Hashes solidity values to a sha3 hash using keccak 256
     *
     * @method soliditySha3
     * @return {Object} the sha3
     */
    var soliditySha3 = function () {
        var args = Array.prototype.slice.call(arguments);

        var hexArgs = _.map(args, _processSoliditySha3Args);

        return utils.sha3('0x'+ hexArgs.join(''));
    };

    module.exports = soliditySha3;