CVE-2019-16761 (JSON, published 2019-11-15T23:15Z)
Description: value: A specially crafted Bitcoin script can cause a discrepancy between the specified SLP consensus rules and the validation result of the slp-validate@1.0.0 npm package. An attacker could create a specially crafted Bitcoin script in order to cause a hard-fork from the SLP consensus. All versions >1.0.0 have been patched.
Severity: MEDIUM (CVSS v3 base score: 6.1)
Weakness: CWE-20 \u2014 Improper Input Validation
The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
Repository: https://github.com/simpleledger/slp-validate
Files changed:
.vscode/settings.json
README.md
lib/crypto.ts
lib/script.ts
lib/slp.ts
package-lock.json
package.json
tsconfig.json
tslint.json
Commit message: 1.0.1 updates:

* add ts linting
* include gs++ validation example


Vulnerable code:
- Add max cache size parameters in ValidatorType1 constructor
import * as crypto from 'crypto';
    static hash256(message: Buffer): Buffer { 
        let hash1 = crypto.createHash('sha256');
        let hash2 = crypto.createHash('sha256');
        OP_1NEGATE : 79,
import { Script } from './script';
import Big from 'big.js';
    "GENESIS" = "GENESIS", 
    "MINT" = "MINT", 
    "SEND" = "SEND"
    "TokenVersionType1_NFT_Parent" = 129
    documentUri: string|Buffer; 
    opcode: number, 
    data: Buffer|null
    static get lokadIdHex() { return "534c5000" }
    static parseOpReturnToChunks(script: Buffer, allow_op_0=false, allow_op_number=false) {
    
        } catch(e) {
            //console.log(e);
            throw Error('Script error');
        if(ops[0].opcode !== Script.opcodes.OP_RETURN)
            throw Error('No OP_RETURN');
        let chunks: (Buffer|null)[] = [];
            if(opitem.opcode > Script.opcodes.OP_16)
            if(opitem.opcode > Script.opcodes.OP_PUSHDATA4) {
                if(opitem.opcode === 80)
                    throw Error('Non-push opcode');
                if(!allow_op_number)
                    throw Error('OP_1NEGATE to OP_16 not allowed');
                if(opitem.opcode === Script.opcodes.OP_1NEGATE)
                else // OP_1 - OP_16
            if(opitem.opcode === Script.opcodes.OP_0 && !allow_op_0){
                throw Error('OP_0 not allowed');
            chunks.push(opitem.data)
        //console.log(chunks);
        return chunks
    }

    static parseChunkToInt(intBytes: Buffer, minByteLen: number, maxByteLen: number, raise_on_Null = false) {
        // # Parse data as unsigned-big-endian encoded integer.
        // # For empty data different possibilities may occur:
        // #      minByteLen <= 0 : return 0
        // #      raise_on_Null == False and minByteLen > 0: return None
        // #      raise_on_Null == True and minByteLen > 0:  raise SlpInvalidOutputMessage
        if(intBytes.length >= minByteLen && intBytes.length <= maxByteLen)
            return intBytes.readUIntBE(0, intBytes.length)
        if(intBytes.length === 0 && !raise_on_Null)
            return null;
        throw Error('Field has wrong length');
    static parseSlpOutputScript(outputScript: Buffer): SlpTransactionDetails {
        let slpMsg = <SlpTransactionDetails>{};
        let chunks: (Buffer|null)[];
        } catch(e) {
            throw Error('Bad OP_RETURN');
        if(chunks.length === 0)
            throw Error('Empty OP_RETURN');
        if(!chunks[0])
            throw Error("Not SLP")
        if(!chunks[0]!.equals(Buffer.from(this.lokadIdHex, 'hex')))
            throw Error('Not SLP');
        if(chunks.length === 1)
        if(!chunks[1])
            throw Error("Bad versionType buffer")
        slpMsg.versionType = <SlpVersionType>Slp.parseChunkToInt(chunks[1]!, 1, 2, true);
        let supportedTypes = [   
                SlpVersionType.TokenVersionType1, 
        if(!supportedTypes.includes(slpMsg.versionType))
            throw Error('Unsupported token type: ' + slpMsg.versionType);
        if(chunks.length === 2)
            throw Error('Missing SLP transaction type');
            let msgType: string = chunks[2]!.toString('ascii')
            slpMsg.transactionType = SlpTransactionType[msgType as keyof typeof SlpTransactionType]
        } catch(_){
            throw Error('Bad transaction type');
        if(slpMsg.transactionType === SlpTransactionType.GENESIS) {
            if(chunks.length !== 10)
                throw Error('GENESIS with incorrect number of parameters');
            slpMsg.symbol = chunks[3] ? chunks[3]!.toString('utf8') : '';
            slpMsg.name = chunks[4] ? chunks[4]!.toString('utf8') : '';
            slpMsg.documentUri = chunks[5] ? chunks[5]!.toString('utf8') : '';
            if(slpMsg.documentSha256) {
                if(slpMsg.documentSha256.length !== 0 && slpMsg.documentSha256.length !== 32)
                    throw Error('Token document hash is incorrect length');
            if(!chunks[7])
                throw Error("Bad decimals buffer")
            slpMsg.decimals = <number>Slp.parseChunkToInt(chunks[7]!, 1, 1, true);
            if(slpMsg.versionType === 0x41 && slpMsg.decimals !== 0)
                throw Error('NFT1 child token must have divisibility set to 0 decimal places.')
            if(slpMsg.decimals > 9)
                throw Error('Too many decimals')
            if(slpMsg.batonVout !== null) {
                if (slpMsg.batonVout < 2)
                    throw Error('Mint baton cannot be on vout=0 or 1');
            if(slpMsg.versionType === 0x41 && slpMsg.batonVout !== null)
                throw Error("NFT1 child token must not have a minting baton!")
            if(!chunks[9])
                throw Error("Bad Genesis quantity buffer")
            if(chunks[9]!.length !== 8)
                throw Error("Genesis quantity must be provided as an 8-byte buffer")
            slpMsg.genesisOrMintQuantity = this.buffer2BigNumber(chunks[9]!);                
            if(slpMsg.versionType === 0x41 && !slpMsg.genesisOrMintQuantity.eq(1))
                throw Error("NFT1 child token must have GENESIS quantity of 1.")
        }
        else if(slpMsg.transactionType === SlpTransactionType.SEND) {
            if(chunks.length < 4)
                throw Error('SEND with too few parameters');
            if(!chunks[3])
                throw Error("Bad tokenId buffer")
            if(chunks[3]!.length !== 32)
                throw Error('token_id is wrong length');
            slpMsg.tokenIdHex = chunks[3]!.toString('hex');
                if(!chunk)
                    throw Error("Bad send quantity buffer.")
                if(chunk.length !== 8)
                    throw Error('SEND quantities must be 8-bytes each.');
            if(slpMsg.sendOutputs.length < 2)
                throw Error('Missing output amounts');
            if(slpMsg.sendOutputs.length > 20)
                throw Error('More than 19 output amounts');
        }
        else if(slpMsg.transactionType === SlpTransactionType.MINT) {
            if(slpMsg.versionType === 0x41)
                throw Error("NFT1 Child cannot have MINT transaction type.")
            if(chunks.length != 6)
                throw Error('MINT with incorrect number of parameters');
            if(!chunks[3])
            if(chunks[3]!.length != 32)
                throw Error('token_id is wrong length');
            slpMsg.tokenIdHex = chunks[3]!.toString('hex');
            slpMsg.batonVout = chunks[4] ? Slp.parseChunkToInt(chunks[4]!,1,1) : null;
            if(slpMsg.batonVout !== null && slpMsg.batonVout !== undefined) {
                if(slpMsg.batonVout < 2)
                    throw Error('Mint baton cannot be on vout=0 or 1');
            if(!chunks[5])
                throw Error("Bad Mint quantity buffer")
            if(chunks[5]!.length !== 8)
                throw Error("Mint quantity must be provided as an 8-byte buffer")
        }
        else
        if(!slpMsg.genesisOrMintQuantity && (!slpMsg.sendOutputs || slpMsg.sendOutputs.length === 0))
    static buffer2BigNumber(amount: Buffer): Big {
        if(amount.length < 5 || amount.length > 8)
        return (new Big(amount.readUInt32BE(0).toString())).times(2**32).plus(amount.readUInt32BE(4).toString());
    static getScriptOperations(script: Buffer) {
        let ops: PushDataOperation[] = [];
                let op: PushDataOperation = { opcode: script[n], data: null }
                if(op.opcode <= Script.opcodes.OP_PUSHDATA4) {
                    if(op.opcode < Script.opcodes.OP_PUSHDATA1)
                    else if(op.opcode === Script.opcodes.OP_PUSHDATA1) {
                    }
                    else if(op.opcode === Script.opcodes.OP_PUSHDATA2) {
                        dlen = script.slice(n, n + 2).readUIntLE(0,2);
                    }
                    else {
                        dlen = script.slice(n, n + 4).readUIntLE(0,4);
                    if((n + dlen) > script.length) {
                        throw Error('IndexError');
                    if(dlen > 0)
                    n += dlen
        } catch(e) {
            //console.log(e);
            throw Error('truncated script')
 
  "version": "1.0.0",
  "version": "1.0.0",
    "mkdirp": "^0.5.1"
    "esModuleInterop": true                 /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

Fixed code:
{
    "files.associations": {
        "*.json": "jsonc"
    }
}
### 1.0.1
- add ts linting to the project
- add example for using gs++ as validation source

- add max cache size parameters in ValidatorType1 constructor
import * as crypto from "crypto";
    public static hash256(message: Buffer): Buffer {
        const hash1 = crypto.createHash("sha256");
        const hash2 = crypto.createHash("sha256");
        OP_1NEGATE: 79,
import { Script } from "./script";
import Big from "big.js";
    "GENESIS" = "GENESIS",
    "MINT" = "MINT",
    "SEND" = "SEND",
    "TokenVersionType1_NFT_Parent" = 129,
    documentUri: string|Buffer;
    opcode: number;
    data: Buffer|null;
    static get lokadIdHex() { return "534c5000"; }
    public static parseOpReturnToChunks(script: Buffer, allowOP_0= false, allowOP_number= false) {

        } catch (e) {
            // console.log(e);
            throw Error("Script error");
        if (ops[0].opcode !== Script.opcodes.OP_RETURN) {
            throw Error("No OP_RETURN");
        }
        const chunks: Array<Buffer|null> = [];
            if (opitem.opcode > Script.opcodes.OP_16) {
            }
            if (opitem.opcode > Script.opcodes.OP_PUSHDATA4) {
                if (opitem.opcode === 80) {
                    throw Error("Non-push opcode");
                }
                if (!allowOP_number) {
                    throw Error("OP_1NEGATE to OP_16 not allowed");
                }
                if (opitem.opcode === Script.opcodes.OP_1NEGATE) {
                } else { // OP_1 - OP_16
                }
            if (opitem.opcode === Script.opcodes.OP_0 && !allowOP_0) {
                throw Error("OP_0 not allowed");
            chunks.push(opitem.data);
        // console.log(chunks);
        return chunks;
    public static parseSlpOutputScript(outputScript: Buffer): SlpTransactionDetails {
        const slpMsg = {} as SlpTransactionDetails;
        let chunks: Array<Buffer|null>;
        } catch (e) {
            throw Error("Bad OP_RETURN");
        }
        if (chunks.length === 0) {
            throw Error("Empty OP_RETURN");
        }
        if (!chunks[0]) {
            throw Error("Not SLP");
        if (!chunks[0]!.equals(Buffer.from(this.lokadIdHex, "hex"))) {
            throw Error("Not SLP");
        }
        if (chunks.length === 1) {
        }
        if (!chunks[1]) {
            throw Error("Bad versionType buffer");
        }
        slpMsg.versionType = (Slp.parseChunkToInt(chunks[1]!, 1, 2, true) as SlpVersionType);
        const supportedTypes = [
                SlpVersionType.TokenVersionType1,
        if (!supportedTypes.includes(slpMsg.versionType)) {
            throw Error("Unsupported token type: " + slpMsg.versionType);
        }
        if (chunks.length === 2) {
            throw Error("Missing SLP transaction type");
        }
            const msgType: string = chunks[2]!.toString("latin1");
            slpMsg.transactionType = SlpTransactionType[msgType as keyof typeof SlpTransactionType];
        } catch (_) {
            throw Error("Bad transaction type");
        if (slpMsg.transactionType === SlpTransactionType.GENESIS) {
            if (chunks.length !== 10) {
                throw Error("GENESIS with incorrect number of parameters");
            }
            slpMsg.symbol = chunks[3] ? chunks[3]!.toString("utf8") : "";
            slpMsg.name = chunks[4] ? chunks[4]!.toString("utf8") : "";
            slpMsg.documentUri = chunks[5] ? chunks[5]!.toString("utf8") : "";
            if (slpMsg.documentSha256) {
                if (slpMsg.documentSha256.length !== 0 && slpMsg.documentSha256.length !== 32) {
                    throw Error("Token document hash is incorrect length");
                }
            }
            if (!chunks[7]) {
                throw Error("Bad decimals buffer");
            }
            slpMsg.decimals = (Slp.parseChunkToInt(chunks[7]!, 1, 1, true) as number);
            if (slpMsg.versionType === 0x41 && slpMsg.decimals !== 0) {
                throw Error("NFT1 child token must have divisibility set to 0 decimal places.");
            }
            if (slpMsg.decimals > 9) {
                throw Error("Too many decimals");
            if (slpMsg.batonVout !== null) {
                if (slpMsg.batonVout < 2) {
                    throw Error("Mint baton cannot be on vout=0 or 1");
                }
            if (slpMsg.versionType === 0x41 && slpMsg.batonVout !== null) {
                throw Error("NFT1 child token must not have a minting baton!");
            }
            if (!chunks[9]) {
                throw Error("Bad Genesis quantity buffer");
            }
            if (chunks[9]!.length !== 8) {
                throw Error("Genesis quantity must be provided as an 8-byte buffer");
            }
            slpMsg.genesisOrMintQuantity = this.buffer2BigNumber(chunks[9]!);
            if (slpMsg.versionType === 0x41 && !slpMsg.genesisOrMintQuantity.eq(1)) {
                throw Error("NFT1 child token must have GENESIS quantity of 1.");
            }
        } else if (slpMsg.transactionType === SlpTransactionType.SEND) {
            if (chunks.length < 4) {
                throw Error("SEND with too few parameters");
            }
            if (!chunks[3]) {
                throw Error("Bad tokenId buffer");
            }
            if (chunks[3]!.length !== 32) {
                throw Error("token_id is wrong length");
            }
            slpMsg.tokenIdHex = chunks[3]!.toString("hex");
                if (!chunk) {
                    throw Error("Bad send quantity buffer.");
                }
                if (chunk.length !== 8) {
                    throw Error("SEND quantities must be 8-bytes each.");
                }
            if (slpMsg.sendOutputs.length < 2) {
                throw Error("Missing output amounts");
            }
            if (slpMsg.sendOutputs.length > 20) {
                throw Error("More than 19 output amounts");
            }
        } else if (slpMsg.transactionType === SlpTransactionType.MINT) {
            if (slpMsg.versionType === 0x41) {
                throw Error("NFT1 Child cannot have MINT transaction type.");
            }
            if (chunks.length !== 6) {
                throw Error("MINT with incorrect number of parameters");
            }
            if (!chunks[3]) {
            }
            if (chunks[3]!.length !== 32) {
                throw Error("token_id is wrong length");
            }
            slpMsg.tokenIdHex = chunks[3]!.toString("hex");
            slpMsg.batonVout = chunks[4] ? Slp.parseChunkToInt(chunks[4]!, 1, 1) : null;
            if (slpMsg.batonVout !== null && slpMsg.batonVout !== undefined) {
                if (slpMsg.batonVout < 2) {
                    throw Error("Mint baton cannot be on vout=0 or 1");
                }
            if (!chunks[5]) {
                throw Error("Bad Mint quantity buffer");
            }
            if (chunks[5]!.length !== 8) {
                throw Error("Mint quantity must be provided as an 8-byte buffer");
            }
        } else {
 }
        if (!slpMsg.genesisOrMintQuantity && (!slpMsg.sendOutputs || slpMsg.sendOutputs.length === 0)) {
        }
    public static parseChunkToInt(intBytes: Buffer, minByteLen: number, maxByteLen: number, raiseOnNull = false) {
        // # Parse data as unsigned-big-endian encoded integer.
        // # For empty data different possibilities may occur:
        // #      minByteLen <= 0 : return 0
        // #      raise_on_Null == False and minByteLen > 0: return None
        // #      raise_on_Null == True and minByteLen > 0:  raise SlpInvalidOutputMessage
        if (intBytes.length >= minByteLen && intBytes.length <= maxByteLen) {
            return intBytes.readUIntBE(0, intBytes.length);
        }
        if (intBytes.length === 0 && !raiseOnNull) {
            return null;
        }
        throw Error("Field has wrong length");
    }

    public static buffer2BigNumber(amount: Buffer): Big {
        if (amount.length < 5 || amount.length > 8) {
        }
        return (new Big(amount.readUInt32BE(0).toString())).times(2 ** 32).plus(amount.readUInt32BE(4).toString());
    public static getScriptOperations(script: Buffer) {
        const ops: PushDataOperation[] = [];
                const op: PushDataOperation = { opcode: script[n], data: null };
                if (op.opcode <= Script.opcodes.OP_PUSHDATA4) {
                    if (op.opcode < Script.opcodes.OP_PUSHDATA1) {
                    } else if (op.opcode === Script.opcodes.OP_PUSHDATA1) {
                    } else if (op.opcode === Script.opcodes.OP_PUSHDATA2) {
                        dlen = script.slice(n, n + 2).readUIntLE(0, 2);
                    } else {
                        dlen = script.slice(n, n + 4).readUIntLE(0, 4);
                    if ((n + dlen) > script.length) {
                        throw Error("IndexError");
                    if (dlen > 0) {
                    }
                    n += dlen;
        } catch (e) {
            // console.log(e);
            throw Error("truncated script");
  "version": "1.0.1",
    "get-caller-file": {
      "version": "1.0.3",
      "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz",
      "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==",
      "dev": true
    },
    "mock-require": {
      "version": "3.0.3",
      "resolved": "https://registry.npmjs.org/mock-require/-/mock-require-3.0.3.tgz",
      "integrity": "sha512-lLzfLHcyc10MKQnNUCv7dMcoY/2Qxd6wJfbqCcVk3LDb8An4hF6ohk5AztrvgKhJCqj36uyzi/p5se+tvyD+Wg==",
      "dev": true,
      "requires": {
        "get-caller-file": "^1.0.2",
        "normalize-path": "^2.1.1"
      }
    },
    "normalize-path": {
      "version": "2.1.1",
      "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz",
      "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=",
      "dev": true,
      "requires": {
        "remove-trailing-separator": "^1.0.1"
      }
    },
    "remove-trailing-separator": {
      "version": "1.1.0",
      "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz",
      "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=",
      "dev": true
    },
    "typescript": {
      "version": "3.6.4",
      "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.6.4.tgz",
      "integrity": "sha512-unoCll1+l+YK4i4F8f22TaNVPRHcD9PA3yCuZ8g5e0qGqlVlJ/8FSateOLLSagn+Yg5+ZwuPkL8LFUc0Jcvksg==",
      "dev": true
    },
    "typescript-tslint-plugin": {
      "version": "0.5.4",
      "resolved": "https://registry.npmjs.org/typescript-tslint-plugin/-/typescript-tslint-plugin-0.5.4.tgz",
      "integrity": "sha512-CQEfGC+p0SoBARI4N2LrGsWJsp4/OE+uKZ68xsWYKHWqMFq4DFQHqOVlK0deEricSN01NmDTqjap63Pw/DHieg==",
      "dev": true,
      "requires": {
        "minimatch": "^3.0.4",
        "mock-require": "^3.0.2",
        "vscode-languageserver": "^5.1.0"
      }
    },
    "vscode-jsonrpc": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-4.0.0.tgz",
      "integrity": "sha512-perEnXQdQOJMTDFNv+UF3h1Y0z4iSiaN9jIlb0OqIYgosPCZGYh/MCUlkFtV2668PL69lRDO32hmvL2yiidUYg==",
      "dev": true
    },
    "vscode-languageserver": {
      "version": "5.2.1",
      "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-5.2.1.tgz",
      "integrity": "sha512-GuayqdKZqAwwaCUjDvMTAVRPJOp/SLON3mJ07eGsx/Iq9HjRymhKWztX41rISqDKhHVVyFM+IywICyZDla6U3A==",
      "dev": true,
      "requires": {
        "vscode-languageserver-protocol": "3.14.1",
        "vscode-uri": "^1.0.6"
      }
    },
    "vscode-languageserver-protocol": {
      "version": "3.14.1",
      "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.14.1.tgz",
      "integrity": "sha512-IL66BLb2g20uIKog5Y2dQ0IiigW0XKrvmWiOvc0yXw80z3tMEzEnHjaGAb3ENuU7MnQqgnYJ1Cl2l9RvNgDi4g==",
      "dev": true,
      "requires": {
        "vscode-jsonrpc": "^4.0.0",
        "vscode-languageserver-types": "3.14.0"
      }
    },
    "vscode-languageserver-types": {
      "version": "3.14.0",
      "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.14.0.tgz",
      "integrity": "sha512-lTmS6AlAlMHOvPQemVwo3CezxBp0sNB95KNPkqp3Nxd5VFEnuG1ByM0zlRWos0zjO3ZWtkvhal0COgiV1xIA4A==",
      "dev": true
    },
    "vscode-uri": {
      "version": "1.0.8",
      "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.8.tgz",
      "integrity": "sha512-obtSWTlbJ+a+TFRYGaUumtVwb+InIUVI0Lu0VBUAPmj2cU5JutEXg3xUE0c2J5Tcy7h2DEKVJBFi+Y9ZSFzzPQ==",
      "dev": true
    },
  "version": "1.0.1",
    "mkdirp": "^0.5.1",
    "typescript-tslint-plugin": "^0.5.4",
    "typescript": "^3.6.4"
    "esModuleInterop": true,                 /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "plugins": [
      { "name": "typescript-tslint-plugin" }
    ]
// You can modify the configuration here with your own.
// Make sure that your json is valid, and if you run into
// other issues, try checking the console for errors.

{
    "extends": ["tslint:recommended"],
    "rules": {} // add additional rules and their configuration
}