script – Earlybirds Invest https://earlybirdsinvest.com Latest Crypto News Fri, 08 Aug 2025 02:51:20 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.11 https://i0.wp.com/earlybirdsinvest.com/wp-content/uploads/2024/12/cropped-New-Project-2024-12-17T235703.455.png?fit=32%2C32&ssl=1 script – Earlybirds Invest https://earlybirdsinvest.com 32 32 240146708 Create a forwarding script using TapRoot address P2TR https://earlybirdsinvest.com/create-a-forwarding-script-using-taproot-address-p2tr/ https://earlybirdsinvest.com/create-a-forwarding-script-using-taproot-address-p2tr/#respond Fri, 08 Aug 2025 02:51:20 +0000 https://earlybirdsinvest.com/create-a-forwarding-script-using-taproot-address-p2tr/

I’m trying to create a transfer script.

The entire script was provided below

import * as bitcoin from "bitcoinjs-lib";
import * as tinysecp from "tiny-secp256k1";
import axios from "axios";
import ECPairFactory from "ecpair";

const ECPair = ECPairFactory(tinysecp);
bitcoin.initEccLib(tinysecp);

const NETWORK = bitcoin.networks.testnet;
const MEMPOOL_API = "https://mempool.space/testnet/api";

// Helper function to validate UTXO
function validateUtxo(utxo: any): void {
  if (
    !utxo.txid ||
    typeof utxo.vout !== "number" ||
    typeof utxo.value !== "number"
  ) {
    throw new Error("Invalid UTXO structure");
  }
  if (!/^(a-fA-F0-9){64}$/.test(utxo.txid)) {
    throw new Error("Invalid UTXO txid format");
  }
}

export async function sendBTC_P2TR({
  wif,
  recipient,
  amountSats,
}: {
  wif: string;
  recipient: string;
  amountSats: number;
}): Promise<{ success: boolean; message: string; txId?: string }> {
  try {
    console.log("🏁 Starting transaction process...");

    // Input validation
    if (!wif || !recipient || !amountSats) {
      throw new Error("Missing required parameters");
    }
    if (typeof amountSats !== "number" || amountSats <= 0) {
      throw new Error("Invalid amount");
    }
    if (!recipient.startsWith("tb1p")) {
      throw new Error("Recipient must be a Taproot testnet address");
    }

    // Key derivation
    const keyPair = ECPair.fromWIF(wif, NETWORK);
    if (!keyPair.privateKey) throw new Error("No private key derived from WIF");

    const privateKey = keyPair.privateKey;
    const internalPubkey = Buffer.from(
      tinysecp.pointFromScalar(privateKey, true)!.slice(1)
    );

    const p2tr = bitcoin.payments.p2tr({ internalPubkey, network: NETWORK });
    const address = p2tr.address!;
    const scriptPubKey = p2tr.output!;

    console.log("📬 Sender Taproot address:", address);

    // Fetch UTXOs
    const { data: utxos } = await axios.get(
      `${MEMPOOL_API}/address/${address}/utxo`
    );
    if (!utxos.length) return { success: false, message: "No UTXOs found" };

    // Estimate fee
    const { data: fees } = await axios.get(
      `${MEMPOOL_API}/v1/fees/recommended`
    );
    const feeRate = Math.max(fees.hourFee || 1, 2);
    const fee = Math.ceil(feeRate * 110); // Estimated vsize for P2TR

    // Select UTXO
    const utxo = utxos.find((u: any) => u.value >= amountSats + fee);
    if (!utxo)
      return {
        success: false,
        message: `No suitable UTXO found (needed ${amountSats + fee} sats)`,
      };

    // Key tweaking
    const tweak = bitcoin.crypto.taggedHash("TapTweak", internalPubkey);
    let tweakedPrivKey = tinysecp.privateAdd(privateKey, tweak);
    if (!tweakedPrivKey) throw new Error("Failed to tweak private key");

    // Build PSBT
    const psbt = new bitcoin.Psbt({ network: NETWORK });
    psbt.addInput({
      hash: utxo.txid,
      index: utxo.vout,
      witnessUtxo: { script: scriptPubKey, value: utxo.value },
      tapInternalKey: internalPubkey,
    });

    psbt.addOutput({ address: recipient, value: amountSats });
    const change = utxo.value - amountSats - fee;
    if (change > 294) {
      // Dust limit
      psbt.addOutput({ address, value: change });
    }

    // Signing (fixed approach)
    const tx = (psbt as any).__CACHE.__TX as bitcoin.Transaction;
    const hash = tx.hashForWitnessV1(0, (scriptPubKey), (utxo.value), 0x00);
    const signature = Buffer.from(tinysecp.signSchnorr(hash, tweakedPrivKey));

    // Update with proper signature format
    psbt.updateInput(0, {
      tapKeySig: signature,
    });

    // Final verification
    const validator = (pubkey: Buffer, msghash: Buffer, sig: Buffer) => {
      return tinysecp.verifySchnorr(msghash, pubkey, sig);
    };
    psbt.validateSignaturesOfInput(0, validator);

    psbt.finalizeAllInputs();
    const txHex = psbt.extractTransaction().toHex();

    // Broadcast
    const { data: txId } = await axios.post(`${MEMPOOL_API}/tx`, txHex, {
      headers: { "Content-Type": "text/plain" },
    });

    return { success: true, message: "Transaction broadcasted", txId };
  } catch (error: any) {
    console.error("Transaction failed:", error.message);
    return {
      success: false,
      message: error?.response?.data || error?.message || "Unknown error",
    };
  }
}

However, I’m facing an error that I can’t understand why

Transaction failed: Request failed with status code 400
❌ Transaction failed: sendrawtransaction RPC error: {"code":-26,"message":"mandatory-script-verify-flag-failed (Invalid Schnorr signature)"}

]]>
https://earlybirdsinvest.com/create-a-forwarding-script-using-taproot-address-p2tr/feed/ 0 52071
What’s wrong with my script? https://earlybirdsinvest.com/whats-wrong-with-my-script/ https://earlybirdsinvest.com/whats-wrong-with-my-script/#respond Mon, 28 Jul 2025 05:08:55 +0000 https://earlybirdsinvest.com/whats-wrong-with-my-script/

There are some issues with the provided BASH scripts for creating and signing Bitcoin transactions using Bitcoin-Cli.

Here is a detailed breakdown of the issue and proposed fixes:

Private key format:

Problem: private_key_1 and private_key_2 are provided as 64 characters hexadecimal strings. However, Bitcoin-Cli expects a private key in wallet import format (WIF) that usually starts with k, l, or 5 and is base58 encoded. Fix: Converts hexadecimal private keys to WIF format. You can use tools like Bitcoin Tools and Online Converters, but make sure they are operating in a safe environment to protect your keys.

Example of conversion using Bitcoin-Cli:

# Convert HEX to WIF for PRIVATE_KEY_1
WIF_PRIVATE_KEY_1=$(bitcoin-cli -regtest dumpprivkey )

# Convert HEX to WIF for PRIVATE_KEY_2
WIF_PRIVATE_KEY_2=$(bitcoin-cli -regtest dumpprivkey )

Replace and The actual Bitcoin address is linked to the private key.

Invalid input_txid:

Problem: input_txid is set to all zeros (0000 … 0000), but this is not a valid transaction ID. This causes CREATERAWTRANSACTION A command that fails because it refers to a transaction that does not exist.

Fix: Use a valid transaction ID from the blockchain (especially because it works with RegTest, make sure the transaction exists).

example:

INPUT_TXID="your_valid_txid_here"

ScriptPubkey Format:

problem: Redeem_script_hex It appears to be for Multisig setup, but I’ll make sure it matches the actual script in UTXO that I’m trying to use.

Fix: Check it Redeem_script_hex Correctly supports UTXO lock scripts. For standard P2SH or P2WSH scripts, make sure the format matches the expected pattern.

Deleted SignRawTransactionWithKey command:

Problem: Depending on the Bitcoin-Cli version, sightrawtransactionwithkey Commands may be deprecated.

Fix: Used sightrawtransactionwithkey If supported. Otherwise, consider using it sightrawtransaction withwallet Alternatively, update the script according to the latest Bitcoin-Cli documentation.

Output address verification:

problem: output_address It starts with 3not a standard prefix for RegTest. In RegTest, addresses usually start with different characters.

RegTest prefix:

Legacy addresses start with: m or n
The P2SH address starts with: 2
BECH32 addresses start with: BCRT1

address 325UUECEQUYRTD28XS2HVAXDAJHM7XZQVF
It does not conform to the standard RegTest address format.

Fix: Check output_address Valid address for the RegTest environment. You can generate a new address using:

# Generate a new legacy address in regtest
bitcoin-cli -regtest getnewaddress "" legacy

# Generate a new P2SH address in regtest
bitcoin-cli -regtest getnewaddress "" p2sh

# Generate a new bech32 address in regtest
bitcoin-cli -regtest getnewaddress "" bech32

Exchange addresses 325UUECEQUYRTD28XS2HVAXDAJHM7XZQVF Use the above command to use the address generated directly from the RegTest Bitcoin node.

Dependencies and Tools:

Problem: The script uses JQ to parse the JSON. Make sure JQ is installed on your system.

Fix: Install JQ if it doesn’t already exist.

# sudo apt-get install jq

Using sequence numbers:

problem: order It is set to 0xffffffff. This is the default and may not be necessary unless you implement certain features such as per-swap (RBF).

Modify: If not required, you can omit the sequence field in the input object.

Overall script enhancements:

Security: Avoid hardcoded private keys in scripts. Consider using environment variables or a major safe management system.

Error Handling: Add a check to ensure that each command runs successfully before proceeding to the next step. This helps you debug the problem more effectively.

example:

# Create raw transaction
UNSIGNED_TX=$(bitcoin-cli -regtest -rpcuser=alice -rpcpassword=password createrawtransaction '({"txid":"'$INPUT_TXID'","vout":'$INPUT_VOUT'})' '{"'$OUTPUT_ADDRESS'":'$VALUE'}')
if ( $? -ne 0 ); then
  echo "Failed to create raw transaction."
  exit 1
fi

# Sign transaction
SIGNED_TX=$(bitcoin-cli -regtest -rpcuser=alice -rpcpassword=password signrawtransactionwithkey "$UNSIGNED_TX" '("'$WIF_PRIVATE_KEY_1'", "'$WIF_PRIVATE_KEY_2'")' '({"txid":"'$INPUT_TXID'","vout":'$INPUT_VOUT',"scriptPubKey":"'$REDEEM_SCRIPT_HEX'","redeemScript":"'$REDEEM_SCRIPT_HEX'"})')
if ( $? -ne 0 ); then
  echo "Failed to sign transaction."
  exit 1
fi

By addressing these issues, the script must function correctly when creating and signing Bitcoin transactions within the RegTest environment.

]]>
https://earlybirdsinvest.com/whats-wrong-with-my-script/feed/ 0 50069
No Room For Doubt: Analyst’s $900K Bitcoin Forecast Follows Familiar Script https://earlybirdsinvest.com/no-room-for-doubt-analysts-900k-bitcoin-forecast-follows-familiar-script/ https://earlybirdsinvest.com/no-room-for-doubt-analysts-900k-bitcoin-forecast-follows-familiar-script/#respond Sat, 31 May 2025 11:37:59 +0000 https://earlybirdsinvest.com/no-room-for-doubt-analysts-900k-bitcoin-forecast-follows-familiar-script/

Reason to trust

Strict editorial policy that focuses on accuracy, relevance, and impartiality

Created by industry experts and meticulously reviewed

The highest standards in reporting and publishing

Strict editorial policy that focuses on accuracy, relevance, and impartiality

Morbi pretium leo et nisl aliquam mollis. Quisque arcu lorem, ultricies quis pellentesque nec, ullamcorper eu odio.

Este artículo también está disponible en español.

Bitcoin’s price slipped to $105,235 today, dropping 1.5% over the past 24 hours and falling 4.2% in the last week. Some market watchers see this dip as a pause before a major move. According to their charts, Bitcoin could be gearing up for another steep gain.

Related Reading

Historical Patterns Point To Rebound

Based on reports from the analyst known as “Mister Crypto,” rounded-bottom formations and ascending triangles have marked every big Bitcoin rally. In 2013, when Bitcoin was trading under $10, it spent months in a smooth, curved base before breaking out and climbing past $1,000.

A similar pattern showed up in 2017. After nearly three years of sideways action, the price finally exploded toward $20,000. The last cycle in 2021 also followed the same playbook, with almost four years of building a wide base before shooting up to nearly $70,000.

Mister Crypto’s chart suggests that the period after 2021 has formed another base. If history plays out the same way, his forecast points to a breakout in 2025 that could send Bitcoin as high as $900,000—a 760% rise from today’s level.

Analyst Charts Re-Accumulation

According to charts shared by another analyst, Bitcoin often moves in stages. First, there’s an initial “leg up” that signals the shift from deep accumulation into a growing bull trend. Then, the price settles into a sideways “re-accumulation” phase before the final run.

BTC is now trading at $103,783. Chart: TradingView

From 2019 through 2021, Bitcoin followed this path closely. Analysts note that from late 2023 into mid-2025, Bitcoin looks to be in that same re-accumulation phase. If this unfolds as in past cycles, the next big upswing could push Bitcoin into the $270,000–$350,000 range before any parabolic spike comes into view.

Long-Term Holders Keep Adding Coins

On-chain data shows long-term holders (addresses that haven’t moved their coins in over 155 days) are still piling on. Between March 3 and May 25, 2025, these holders increased their overall supply by nearly 1.40 million BTC.

That pushed long-term holdings from 14,354,000 BTC to 15,739,400 BTC. In previous bull markets—like those in 2013, 2017, and 2021—long-term holders often sold during the rallies to lock in profit.

Related Reading

Today, though, they seem content to hold. If large pockets of Bitcoin remain off exchanges, fewer coins are available for new buyers. That could tighten supply and make sharp moves more likely once demand picks up.

Bitcoin price down in the last week. Source: Coingecko

Looking Ahead In Uncertain Market

Bitcoin has lost momentum recently, but many analysts feel these dips won’t last. At $105K region, the price sits below last week’s levels.

Based on reports, some see that as healthy consolidation before a bigger run. Others warn that global interest rates, regulation, and macro factors could slow things down.

Featured image from Pexels, chart from TradingView

]]>
https://earlybirdsinvest.com/no-room-for-doubt-analysts-900k-bitcoin-forecast-follows-familiar-script/feed/ 0 39330
Threat actors abuse Google Apps Script in evasive phishing attacks https://earlybirdsinvest.com/threat-actors-abuse-google-apps-script-in-evasive-phishing-attacks/ https://earlybirdsinvest.com/threat-actors-abuse-google-apps-script-in-evasive-phishing-attacks/#respond Thu, 29 May 2025 16:33:23 +0000 https://earlybirdsinvest.com/threat-actors-abuse-google-apps-script-in-evasive-phishing-attacks/

Threat actors abuse Google Apps Script in evasive phishing attacks

Threat actors are abusing the ‘Google Apps Script’ development platform to host phishing pages that appear legitimate and steal login credentials.

This new trend was spotted by security researchers at Cofense, who warn that the fraudulent login window is “carefully designed to look like a legitimate login screen.”

“The attack uses an email masquerading as an invoice, containing a link to a webpage that uses Google Apps Script, a development platform integrated across Google’s suite of products,” Cofense explains.

“By hosting the phishing page within Google’s trusted environment, attackers create an illusion of authenticity. This makes it easier to trick recipients into handing over sensitive information.”

Legitimate service abuse

Google Apps Script is a JavaScript-based cloud scripting platform from Google that allows users to automate tasks and extend the functionality of Google Workspace products like Google Sheets, Docs, Drive, Gmail, and Calendar.

These scripts run on a trusted Google domain under “script.google.com,” which is on the allowlist of most security products.

Attackers write a Google Apps Script that displays a fake login page to capture the credentials victims enter. The data is exfiltrated to the attacker’s server via a hidden request.

Phishing page hosted on Google infrastructure
Phishing page hosted on Google infrastructure
Source: Cofense

As the platform allows anyone with an account to publish a script as a public web app, giving it a Google domain, the threat actors can easily share it with the victims via a phishing email that won’t trigger any warnings.

The phishing email contains an invoice payment or tax-related call to action for the recipient, linking to the malicious Google-hosted phishing page.

Sample of a phishing email used in the attacks
Sample of a phishing email used in the attacks
Source: Cofense

After the victim enters their username and password, they are redirected to the legitimate service that was spoofed to lower suspicion and give threat actors time to exploit the stolen data.

Google Apps Script appears to be the new focus of phishing actors that look for legitimate platforms to abuse for evasion and operational efficiency.

In this case, it also gives the attackers the flexibility to remotely adjust their script without having to resend a new link, switching to a different lure without much effort.

An effective defense measure would be to configure email security to scrutinize cloud service links and, if possible, block access to Google Apps Script URLs altogether, or at least flag them as potentially dangerous.

BleepingComputer has contacted Google to ask if they plan to implement any anti-abuse measures in response to Cofense’s findings, but we have not heard back as of publication.

Red Report 2025

Based on an analysis of 14M malicious actions, discover the top 10 MITRE ATT&CK techniques behind 93% of attacks and how to defend against them.

]]>
https://earlybirdsinvest.com/threat-actors-abuse-google-apps-script-in-evasive-phishing-attacks/feed/ 0 38994
Is it possible to create a multi-party calculation (MPC) P2TR custom spending script? https://earlybirdsinvest.com/is-it-possible-to-create-a-multi-party-calculation-mpc-p2tr-custom-spending-script/ https://earlybirdsinvest.com/is-it-possible-to-create-a-multi-party-calculation-mpc-p2tr-custom-spending-script/#respond Thu, 10 Apr 2025 12:21:43 +0000 https://earlybirdsinvest.com/is-it-possible-to-create-a-multi-party-calculation-mpc-p2tr-custom-spending-script/

I’m working on designing custom spending scripts UTXO I use A P2TR (Pay-to-Taproot) Output. Expense terms require signatures from a multi-party calculation (MPC) wallet that is verified upon spending. In my research I found OP_CHECKMULTISIGsupports multi-sig wallets, but my use cases are different as I specifically aim to integrate MPC wallet signature checks within Taproot scripts rather than standard multi-sig setups.

Can you provide guidance or examples on how to implement this in a P2TR script? Are there specific opcodes, unique features (such as Schnorr Signatures or Script Leaves), or are there any techniques to explore to achieve this custom spending term?

]]>
https://earlybirdsinvest.com/is-it-possible-to-create-a-multi-party-calculation-mpc-p2tr-custom-spending-script/feed/ 0 30058
For failed check (multi) SIG operation errors, the script must be zeroed https://earlybirdsinvest.com/for-failed-check-multi-sig-operation-errors-the-script-must-be-zeroed/ https://earlybirdsinvest.com/for-failed-check-multi-sig-operation-errors-the-script-must-be-zeroed/#respond Thu, 03 Apr 2025 02:09:49 +0000 https://earlybirdsinvest.com/for-failed-check-multi-sig-operation-errors-the-script-must-be-zeroed/

For P2SH transactions, an example redemption script:

 CScript((my_private_key.pub,OP_CHECKSIG,OP_IF,OP_1,OP_ELSE,OP_1,OP_ENDIF))

Works if the expression is true. Executes the IF statement. That is, the first signature matches. However, if the initial signature does not match the public key, instead of performing another statement, the site will return:

SendRawTransaction RPC Error-26: Non-monitoring-Script-Verify-Flag (must be zero if signature fails (multi-)SIG operation)

but, VerifyScript(txin.scriptSig, (txin_scriptPubKey), tx, 0, (SCRIPT_VERIFY_P2SH,)) Does not throw errors. This is also how you generate a signature.

def create_OP_CHECKSIG_signature(tx, txin_scriptPubKey, seckey):
    
    sighash = SignatureHash(txin_scriptPubKey, tx, 0, SIGHASH_ALL)
    signature = seckey.sign(sighash) + bytes((SIGHASH_ALL))
    return signature
#usage
sig = create_OP_CHECKSIG_signature(tx, redeemscript, my_private_key)

Any help is appreciated.

]]>
https://earlybirdsinvest.com/for-failed-check-multi-sig-operation-errors-the-script-must-be-zeroed/feed/ 0 28694
I’m trying to use UTXO in a custom script https://earlybirdsinvest.com/im-trying-to-use-utxo-in-a-custom-script/ https://earlybirdsinvest.com/im-trying-to-use-utxo-in-a-custom-script/#respond Mon, 31 Mar 2025 19:11:58 +0000 https://earlybirdsinvest.com/im-trying-to-use-utxo-in-a-custom-script/

To unlock, the lock script requires three numbers with a total of 15 and a maximum of less than 8. So, after replicating this script in Python, replicating the top 3, removing them to see if they are 15, then checking if each is less than 8.

ex2a_txout_scriptPubKey = (OP_3DUP,OP_8,OP_LESSTHAN,OP_VERIFY,OP_8,OP_LESSTHAN,OP_VERIFY,OP_8,OP_LESSTHAN,OP_VERIFY,OP_ADD,OP_ADD,OP_15,OP_EQUALVERIFY)

Send with this function response = send_from_P2PKH_transaction(amount_to_send, txid_to_spend, utxo_index, ex2a_txout_scriptPubKey)

def send_from_P2PKH_transaction(amount_to_send, txid_to_spend, utxo_index, txout_scriptPubKey):
    # Step 1: Create the txin
    txin = CMutableTxIn(COutPoint(lx(txid_to_spend), utxo_index)) #now we have txin

    # Step 2: Create the txout
    txout = CMutableTxOut(amount_to_send * COIN, CScript(txout_scriptPubKey))

    # Step 3: Create the transaction
    tx = CMutableTransaction((txin), (txout))

    # Step 4: Create the txin_scriptPubKey (from the address holding the UTXO)
    txin_scriptPubKey = my_address.to_scriptPubKey()

    # Step 5: Create the signature
    sig = create_OP_CHECKSIG_signature(tx, txin_scriptPubKey, my_private_key)

    # Step 6: Set the txin's scriptSig value (signature + public_key)
    txin.scriptSig = CScript((sig, my_public_key))

    # Verify the transaction
    VerifyScript(txin.scriptSig, txin_scriptPubKey, tx, 0, (SCRIPT_VERIFY_P2SH,))

    # Broadcast the transaction
    return broadcast_transaction(tx)

It works with classic P2PKH, but with txout_scriptpubkey the response is

`400 Bad Request sendrawtransaction RPC error -26: scriptpubkey`

Any help is appreciated, I don’t know where I went wrong in the script. I first used 8, but I had to use OP_8, but it still doesn’t work. Edit: I won’t accept that either "(OP_5, OP_EQUAL)". You cannot accept anything other than P2PKH.

]]>
https://earlybirdsinvest.com/im-trying-to-use-utxo-in-a-custom-script/feed/ 0 28267
Python script – Ckeys not extracted https://earlybirdsinvest.com/python-script-ckeys-not-extracted/ https://earlybirdsinvest.com/python-script-ckeys-not-extracted/#respond Fri, 28 Feb 2025 16:08:15 +0000 https://earlybirdsinvest.com/python-script-ckeys-not-extracted/

I have this code:

#!/usr/bin/env python3

# pip3 install pycryptodome bsddb3

import os
import bsddb3.db as bdb
import struct

def extract_keys(wallet_path):
    try:
        # Open the wallet.dat file
        db_env = bdb.DBEnv()
        db_env.open(os.path.dirname(wallet_path), bdb.DB_CREATE | bdb.DB_INIT_MPOOL)
        db = bdb.DB(db_env)
        db.open(wallet_path, "main", bdb.DB_BTREE, bdb.DB_RDONLY)

        mkey, ckeys = None, ()

        for key, value in db.items():
            if key.startswith(b'\x04mkey'):
                mkey = value  # Extract master key
            elif key.startswith(b'\x07ckey'):
                ckeys.append(value)  # Extract crypted keys

        db.close()
        db_env.close()

        return {"mkey": mkey, "ckeys": ckeys}

    except Exception as e:
        print(f"Error: {e}")
        return None

if __name__ == "__main__":
    for infile in os.listdir('.'):
        if os.path.isfile(infile) and infile(-4:)=='.dat':
            result = extract_keys(infile)

            if result:
                print(f"File: {infile}")
                print(f"mkey: {result('mkey').hex() if result('mkey') else 'Not found'}")
                print(f"ckey: {(ckey.hex() for ckey in result('ckeys'))}\n")
            else:
                print("Failed to extract keys.")

Mkeys extracts, but ckeys don’t. How to fix it?

Do you want to properly extract MKEY?

]]>
https://earlybirdsinvest.com/python-script-ckeys-not-extracted/feed/ 0 22447
Cannot generate correct P2SH-P2WSH address from specified redemption script https://earlybirdsinvest.com/cannot-generate-correct-p2sh-p2wsh-address-from-specified-redemption-script/ https://earlybirdsinvest.com/cannot-generate-correct-p2sh-p2wsh-address-from-specified-redemption-script/#respond Sun, 23 Feb 2025 09:21:58 +0000 https://earlybirdsinvest.com/cannot-generate-correct-p2sh-p2wsh-address-from-specified-redemption-script/

Could you provide the generated code? I’m struggling to generate the P2SH-P2WSH address from the specified redemption script. In reality, there is no key to the witness program. …In this case I just wanted to double check if the generated address and the specified address were the same

Transaction Spec
Private Key 1: 39dc0a9f0b185a2ee56349691f34716e6e0cda06a7f9707742ac113c4e2317bf
Private Key 2: 5077ccd9c558b7d04a81920d38aa11b4a9f9de3b23fab45c3ef28039920fdd6d
Redeem Script (ASM): OP_2 032ff8c5df0bc00fe1ac2319c3b8070d6d1e04cfbf4fedda499ae7b775185ad53b 039bbc8d24f89e5bc44c5b0d1980d6658316a6b2440023117c3c03a4975b04dd56 OP_2 OP_CHECKMULTISIG
Redeem Script (HEX): 5221032ff8c5df0bc00fe1ac2319c3b8070d6d1e04cfbf4fedda499ae7b775185ad53b21039bbc8d24f89e5bc44c5b0d1980d6658316a6b2440023117c3c03a4975b04dd5652ae
Transaction should contain exactly 1 input with:
Outpoint:
Hash: 0000000000000000000000000000000000000000000000000000000000000000
Index: 0
Sequence: 0xffffffff
Transaction should contain exactly 1 output with:
Value: 0.001
Address: 325UUecEQuyrTd28Xs2hvAxdAjHM7XzqVF
Locktime: 0

I’m doing this in Python

# Given Redeem Script (HEX)
redeem_script_hex = "5221032ff8c5df0bc00fe1ac2319c3b8070d6d1e04cfbf4fedda499ae7b775185ad53b21039bbc8d24f89e5bc44c5b0d1980d6658316a6b2440023117c3c03a4975b04dd5652ae"
script_bytes = bytes.fromhex(redeem_script_hex)
sha256_hash = hashlib.sha256(script_bytes).digest()
redeem_script_hash = hashlib.new("ripemd160", sha256_hash).digest()
prefixed_hash = b'\x05' + redeem_script_hash
checksum = hashlib.sha256(hashlib.sha256(prefixed_hash).digest()).digest()(:4)
final_data = prefixed_hash + checksum
address = base58.b58encode(final_data).decode()
print(address)

Putput appears

h-multisig-tx-jatin-2708/python$ python main.py
39C5GaHDocqYVgyCq2TrMfknTL45LPPcKF

But it should come

Address: 325UUecEQuyrTd28Xs2hvAxdAjHM7XzqVF (as given in ques)

Can anyone explain why the addresses are different, as the witness appears to be missing…?

]]>
https://earlybirdsinvest.com/cannot-generate-correct-p2sh-p2wsh-address-from-specified-redemption-script/feed/ 0 21340