Categories
Bitcoin Cryptocurrency Mastering Development

How to sign a 2-of-2 multisig address?

I want to implement 2-of-2 multisig in bitcoinj, and I implement the methods which are used to sign the first time and the second time. But there is a bug that using the same key for the first signing and second signing can also pass the transaction verification and can be broadcast. Where the mistake is?

sign_first_time(Transaction spendTx, String firstkey,String redeemScript_String){
        ECKey key1 = HexToECKey(firstkey);
        Script redeemScript = new Script(hexStringToByteArray(redeemScript_String));
        Sha256Hash sighash = spendTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
        ECKey.ECDSASignature ecdsaSignature = key1.sign(sighash);
        TransactionSignature transactionSignarture = new TransactionSignature(ecdsaSignature, Transaction.SigHash.ALL, false);
        Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(Arrays.asList(transactionSignarture), redeemScript);
        TransactionInput input = spendTx.getInput(0);
        input.setScriptSig(inputScript);
       }
sign_second_time(String transactionString,String secondkey){
        Transaction spendTx = new Transaction(params, hexStringToByteArray(transactionString));
        Script inputScript = spendTx.getInput(0).getScriptSig();
        List<ScriptChunk> scriptChunks = inputScript.getChunks();
        List<TransactionSignature> signatureList = new ArrayList<TransactionSignature>();
        Iterator<ScriptChunk> iterator = scriptChunks.iterator();
        Script redeemScript = null;

        while (iterator.hasNext())
        {
            ScriptChunk chunk = iterator.next();

            if (iterator.hasNext() && chunk.opcode != 0)
            {
                TransactionSignature transactionSignarture = TransactionSignature.decodeFromBitcoin(chunk.data, false,false);
                signatureList.add(transactionSignarture);
            } else
            {
                redeemScript = new Script(chunk.data);
            }
        }
        Sha256Hash sighash = spendTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
        ECKey.ECDSASignature secondSignature;
        ECKey key2 = HexToECKey(secondkey);
        secondSignature = key2.sign(sighash);
        TransactionSignature transactionSignarture = new TransactionSignature(secondSignature, Transaction.SigHash.ALL, false);
        signatureList.add(transactionSignarture);
        inputScript = ScriptBuilder.createP2SHMultiSigInputScript(signatureList, redeemScript);
        spendTx.getInput(0).setScriptSig(inputScript);
        return spendTx;
    } 

Leave a Reply

Your email address will not be published. Required fields are marked *