# all files / packages/web3-utils/src/ soliditySha3.js

88.79% Statements 103/116
85.96% Branches 98/114
100% Functions 8/8
88.79% Lines 103/116

    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
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246

    3×
    3×
    3×

    3×

    120×
    2×
    118×
    1×
    117×
    2×
    115×
    2×
    113×

    113×

    113×

    113×

    113×

    3×
    78×
    78×

    3×
    19×
    19×

    3×
    60×
    60×
    21×
    13×

    8×

    39×
    8×
    31×

    31×
    31×

    3×

    120×
    120×

    120×

    17×
    1×

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

    2×

    9×
    2×

    7×

    78×

    78×

    18×

    18×
    6×

    18×
    1×

    17×
    60×

    37×

    37×
    37×

    37×

    37×
    23×

    23×

    23×
    23×

    23×
    15×

    8×

    3×

    107×
    1×

    106×
    106×

    106×
    80×
    80×

    26×
    26×

    26×
    13×

    106×
    26×

    106×
    19×
    19×
    2×

    17×

    104×
    17×
    33×

    16×

    87×
    84×

    3×

    85×

    85×

    78×

    3×
     /*
     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) {
        /*jshint maxcomplexity:false */

        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.isHex(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');
        }
    };

    var _solidityPack = function (type, value, arraySize) {
        /*jshint maxcomplexity:false */

        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);
        }
    };

    var _processSoliditySha3Args = function (arg) {
        /*jshint maxcomplexity:false */

        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','');
        }

    };

    /**
     * Hashes solidity values to a sha3 hash using keccak 256
     *
     * @method soliditySha3
     * @return {Object} the sha3
     */
    var soliditySha3 = function () {
        /*jshint maxcomplexity:false */

        var args = Array.prototype.slice.call(arguments);

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

        // console.log(args, hexArgs);
        // console.log('0x'+ hexArgs.join(''));

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

    module.exports = soliditySha3;