text:
Recommended way of printing a cold wallet
I'm considering making cold paper wallets (for multiple cryptocurrencies) for offline storage in a safe deposit box.
Before accessing the safe deposit box, my identity is checked and I must show my key, so I consider storing the paper wallets non-encrypted.
They are a lot of tutorials on how to generate a wallet on an offline computer, but I'm searching for an efficient way of transferring the wallets to the paper.
Here are the options I have considered, and I would like your opinion.
Handwriting
In a technical point of view, handwriting the wallet key seems secure but tedious. I'm not very confident about reading my own handwriting in ten years, especially in base56 , not talking about my children reading it.
Low-cost laser printer
Buying a $60 printer that should be supported by the offline computer. I think that kind of offline printer will be unlikely to store my private keys and even more unlikely to transmit them.
typewriter
Buying a second hand typewriter and typing the key on it. Seems pretty secure and relatively easy, if the key can't be extracted from the ribbon.
Label printer
Label printers can probably work without a driver, just by echoing the key through the serial port, but thermal paper won't last enough, thermal transfer can be read on the ribbon and matrix printers are expensive.
Embossing label maker
I'm pretty sure that this one can't be hacked and can be read by anyone in thirty years, but they don't have upper and lowercase required for base56. Writing the key in hexadecimal can be a solution.

You can use BIP 38 encryption to encrypt your private key and then just print out your private key normally. BIP 38 will encrypt the private key using AES with a passphrase of your choice (so make sure that it is a secure one) and encode it using Base58 Check Encoding so you will get a string that is your encrypted private key. Because it is encrypted, you can print it out normally without risking the private key being revealed as the printer and any devices on the network will only see the encrypted string and not the actual private key.
The only caveat is that if you forget your passphrase, you lose the private key. One way around that would be to write your password on the printout.

Seems a good idea, but I think handwriting a good passphrase is as difficult as handwriting the full wallet key.

if you are handling large amounts of value and dont mind spending a bit more than expected, you can buy literally any printer you like.
just make the keys offline, print them offline, then properly exterminate the printer (and maybe the computer as well). I would use fire. lots of fire.
extra points if you make them while enclosed in a faradays cage using a battery for your energy source.
if you plan for the long-term, consider how well paper, die and similar age. laminating the paper might be a good idea.


text:
How to handle an old, abandoned Litecoin withdrawal from btc-e.com
In 2013 I bought some litecoins on btc-e.com.
I noticed this website is down by now.
I found a e-mail from 11/2013:
"Dear (my login name),
We received a request to withdraw 25.87814001 LTC on purse Lh2x1hcGiRnWJRwGdfJP26sB4zw8j54e6m
To confirm the transaction, go to:
(Removed link)
To cancel a transaction, go to:
(Removed link)
IP: (my ip address)
Login: (my login)
Regards,
Administration of BTC-E.COM"
On https://live.blockcypher.com/ltc/address/Lh2x1hcGiRnWJRwGdfJP26sB4zw8j54e6m/
I found this exact same transaction. Does this mean it still is in the wallet of btc-e? Or is this my external wallet it is transfered to?
Thanks in advance

I had the exact same issue, even tracked it down by finding the withrdawal email from a withdrawal that I guess didn't go through.  My account is https://live.blockcypher.com/ltc/address/LcSLWWRpDtjpuiDXQnJPXwVvVtZGqeJNNa/.
Unfortunately I got the exact same email reply as you as well.  Maybe, there would be some legal action options, but that seems like a long shot.

Hello Ryan, thanks for your reply. You say you 'had' the exact issue. Is it fixed yet? What did you try so far?

Sorry, I haven't gotten the litecoins back, I've mostly given up hope.  Contacting wex.nz was the main thing I attempted.

Thanks for your reply. I can't believe we are the only two people with this problem

I sent a message to the support centre of the new exchange (WEX.nz).
I got this automated reply:
"Hello!
We informed in the news that we don't possess historical data on transaction and orders of the old platform, that's why we cannot approve or deny your words about funds deposit. The funds were credited to the new platform WEX.nz in the amount shown in your profile. During the period after BTCE closing and before WEX opening, all transactions were fulfilled out of control of the old platform as well out of control of the new one."
In my profile I got 0.00005462 Bitcoin and 0.00005462 Bitcoin Cash. Thats all.. It's worth about 1 USD.
How can I get those litecoins that still are on my address?
Thanks in advance

The provided evidence suggests, that the withdrawal never took place as the funds are still at the mentioned address.
Hopefully either

you have a backup of the private key of that address
you are able to (still somehow) contact btc-e.com and get these keys

With that you can load them into another litecoin client.

So this address is a address in the btc-e wallet? Unfortunately I don't have the private keys. If you or someone else could help me with this, I would give you a nice reward if I'm able to succesfully recover the litecoins.

It seems like your litecoins are in that address (Lh2x1hcGiRnWJRwGdfJP26sB4zw8j54e6m), and have been untouched.
To claim it, you must find the exchange this address is linked too and see if the exchange has your correct litecoin balance.
To answer your question, this means that it is no longer in the wallet of btc-e as that address has the correct amount of funds in it.

Thank you for your reply. Is this address the btc-e address or is it my address on another wallet? How do I find the exchange where this address is linked to?
Thanks in advance

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Connecting full nodes within a LAN to speed up blockchain sync
Bitcoin core v0.14.0 seems to be a lot quicker than previous versions, to the point where syncing the full blockchain now seems to be IO-bound rather than CPU-bound: When running top I used to see my CPU running at full capacity (indicating that network IO was not the limiting factor). This is no longer the case it seems, and the speed of network IO seems to be a relevant factor in the time it takes to sync a full blockchain...
Now we always have some new hardware to set up, or some new OS to try out and invariably we find ourselves in the position of building and installing bitcoind followed by a blockchain sync. Now that network speed matters, it would make a lot of sense to try and source the blockchain data from another full node we happen to be running on the same LAN, rather than fetching the data externally from a random peer connection. So my question is:
Assuming I have another full node running on the same LAN, how do I set up the config file of the new node to ensure it connects to this local node so as to benefit from the increased network speed? (This question assuming both nodes are IPv4). How do I change these settings if the running full node is on Tor while the new node is IPv4, or when the running node is IPv4 and the new node is on Tor?
EDIT: following the suggestions from the comment, I have tried to add the line:
addnode=192.168.0.2:8333

in the config file of the new (ipv4) node where 192.168.0.2 is the local ip of the established (tor) node. My tor node config file is as follows:
txindex=1
debug=mempool
daemon=1
#onlynet=onion # commented out to allow local ipv4 connection
onion=127.0.0.1:9050
port=8333
listen=1
bind=127.0.0.1:8333
externalip=<myexternaltoraddress>.onion
seednode=<seed1>.onion
...
banscore=10000
bantime=11

I have also made sure my firewall on the tor node server is properly set up
$ sudo ufw allow 8333

However, my tor node is refusing the connection request as can be seen from the new node debug:
2017-03-31 13:21:50 connect() to 192.168.0.2:8333 failed after select(): Connection refused (111)

The 'connect' cli arg (alternative to addnode) seems possible for this situation?  described in dot-conf here https://en.bitcoin.it/wiki/Running_Bitcoin#Bitcoin.conf_Configuration_File

@sven If you have found an acceptable answer yourself, you should post it as an answer, not edit it into your question. At this point, it is unclear what you're still asking for.

@pieter thank you have amended accordingly.

Ok got it, it seems you need to remove the line bind=127.0.0.1:8333 from the config file, and (surprisingly) you can keep the setting onlynet=onion (you still can connect via ipv4 on the LAN). So the existing Tor node can be configured as follows:
txindex=1
debug=mempool
daemon=1
onlynet=onion
onion=127.0.0.1:9050
port=8333
listen=1
externalip=<myexternaltoraddress>.onion
seednode=<seed1>.onion
[...]
seednode=<seedk>.onion
banscore=10000
bantime=11

and the new local ipv4 node can be configured as follows:
txindex=1
debug=mempool
daemon=1
connect=192.168.0.xxx:8333

With these settings, the Tor node works as normal with Tor only connections (inbound and outbound) with the exception of the local ipv4 connection from the new node.

bind= controls incoming connections. If you bind to localhost, you can only accept incoming connections. onlynet= controls selection for outgoing connections.

@pieter thank you will experiment again in the light of comment

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Maintaining Tor hidden service onion address over new hardware
My bitcoin Tor node recently suffered a hard disk failure. After changing the hardware, re-installing Linux and bitcoind, setting up Tor for a hidden service, I realized (obviously !) that my external onion address had to change. So my question is: what do I need to do to ensure I keep the same onion address the next time my node suffers unrecoverable failure? Looking at the directory /var/lib/tor/bitcoin_service, I can see two files hostname and private_key where the former does contain my onion address (which I think is related to my private key). So I am guessing all I need to do is back up these files and restore them in my new system (while setting up /etc/tor/torrc and bitcoin.conf appropriately of course, as explained here). Do I need more?
EDIT: it seems that simply importing the files hostname and private_key into a new system (having properly defined /etc/tor/torrc and bitcoin.conf) does not work (the node fails to connect to Tor network). So Tor probably maintains additional state apart from these two files. So the question remains open: how to set up a new system so as to keep existing onion address.

Depending on the version of Bitcoin Core and Tor you are using, there is the possibility that your installation was actually making use of Tor control and not actually using the configuration from your torrc. Have a look in the /.bitcoin/ folder for onion_private_key and try exiting Bitcoin Core, putting that file back in place from your old HDD and, restart Bitcoin Core.
I do not know if you will also need to do the same for the Tor auth cookie /run/tor/control.authcookie?
There is an updated setup guide for running Bitcoin Core and Tor on Bitcoin.SE right here.


text:
Help! About how to spend OP_checksigadd Multi-sig
I write a simple taproot-based script in bitcoinjs, like:
<pk1> OP_CHECKSIG <pk2> OP_CHECKSIGADD <pk3> OP_CHECKSIGADD OP_2 OP_EQUAL
It should be a 3-2 threshold account, that require 2 signature. However, it actually required 3 signature, if we only sign it with 2 keypair, it will occur:
Operation not valid with the current stack size
So how do I able to spend this taproot address, with only 2 valid keypair?
Here is the code used to formulate the address and spend:
const leafKeys = [];
const leafPubkeys = [];
const leafKeys_WIF = [];

for (let i = 0; i < num; i++) {
    const leafKey = ECPair.makeRandom({ network });
    leafKeys.push(leafKey);
    leafPubkeys.push(toXOnly(leafKey.publicKey).toString('hex'));
    leafKeys_WIF.push(leafKey.toWIF())
}

// It returns the script that I wrote before
const leafScript = asm_builder(leafPubkeys, threshold);

const scriptTree: Taptree =
{
    output: leafScript,
};

const redeem = {
    output: leafScript,
    redeemVersion: LEAF_VERSION_TAPSCRIPT,
};

const p2tr = bitcoin.payments.p2tr({
    internalPubkey: toXOnly(keypair.publicKey),
    scriptTree,
    redeem,
    network: choose_network(`regtest`),
});

console.log(`Waiting till UTXO is detected at this Address: ${p2tr.address!}`)

let temp_trans = await pushTrans(p2tr.address!)
console.log("the new txid is:", temp_trans)

const utxo = await getUTXOfromTx(temp_trans, p2tr.address!)

let psbt_origin: string = build_psbt(redeem, [utxo], p2tr.address, "bcrt1q5hk8re6mar775fxnwwfwse4ql9vtpn6x558g0w", "regtest", p2tr, amt, fee)
let psbt_ = ''

for (var i = 0; i < threshold; i++) {
    psbt_ = sign_psbt(psbt_origin, leafKeys_WIF[i], "regtest")
    psbt_origin = psbt_
}

const txhex = await pay_psbt_hex(psbt_origin, num - threshold, "regtest")

Solution:
Based on the answer below, I find a way to spending the taproot address, which is by pushing a new tapscripsig into the psbt.data.inputs.
let psbt = Psbt.fromBase64(psbt_)

for (let i = 0; i < psbt.data.inputs.length; i++) {
    for (let j = threshold; j < sign_num; j++) {
        psbt.data.inputs[i].tapScriptSig?.push({
            leafHash: psbt.data.inputs[i].tapScriptSig![0].leafHash,
            // pks here must be the correct pk of the tapscript, exactly equal to the reedem.output
            pubkey: pks[j],
            signature: Buffer.from("")
        });
    }
}

psbt.finalizeAllInputs();

Can you add the complete raw transaction to your post?

Sure, it was a script built in bitcoinJS

You must make sure there is a stack item "signature" for each pubkey that did not sign. This item is not actually a signature, it must be an empty byte vector.

OP_CHECKSIG and OP_CHECKSIGADD both require at least two stack items. The top stack item will be interpreted as the public key, and the next stack item the signature. OP_CHECKSIGADD requires a third stack item which is a counter. If the signature is valid, it will push a stack item that is the counter + 1, otherwise it pushes just the counter.
In order for this script to execute, you must still provide it sufficient stack items. So each OP_CHECKSIGADD for a pubkey that did not sign still needs something to be the signature. But that signature does not need to be valid. BIP 342 requires that such invalid signatures must be an empty byte vector.

Well I have tried this approach by adding the partial sign in the tapscript, which is like:
(1) psbt.data.inputs[0].tapScriptSig.push(Buffer.from("0x0")), but it occur "mandatory-script-verify-flag-failed (Invalid Schnorr signature size)".
(2) Use psbt.signinput(0, keypair), but with a random keypair, it occur "cannot sign input #0 with key

I wonder how could i added this "single 0 byte"

Taproot does not have a "scriptSig" in the same way that scriptSig exists for non-segwit scripts. This field is probably something else, and so the wrong place to put your 0 bytes. I am not familiar with bitcoin-js so cannot help you with specifics. However, it is generally the job of the PSBT finalizer to figure out where in the stack signatures should go, including the 0 bytes. Since it is not doing that, you should open an issue with them.

@AvaChow The "invalid" argument to failed OP_CHECKSIGs is not a single 0 byte; it must be an empty byte sequence.

I'll try Buffer.from("")

Thank you guys, I have find the right way to do it

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Is the trailing pathing in multi-sig descriptors necessary?
I created a multisig wallet with BlueWallet, and I want to convert the config file to a descriptor:

Name: Multisig Vault
Policy: 2 of 3
Derivation: m/48'/0'/0'/2'
Format: P2WSH
1E74CA69: xpub65........................Qwg1Wd
9F40E694: xpub74hnJ........................cWoEszidc
derivation: m/48'/0'/2'/2'
B5B630B5: xpub6F9A........................Rb1VjK

I see in the docs that when making a wsh(sortedmulti()) descriptor, the keys usually have trailing pathing (example: [e6807791/44h/1h/0h]tpubDDAfvogaaAxaFJ6c15ht7Tq6ZmiqFYfrSmZsHu7tHXBgnjMZSHAeHSwhvjARNA6Qybon4ksPksjRbPDVp7yXA1KjTjSd5x18KHqbppnXP1s/0/*  ---> Here I am talking about the /0/*). I also saw in the docs that you want to make 2 descriptors; 1 for change addresses and 1 for regular addresses : "Now the multisig is created by importing the external and internal descriptors: wsh(sortedmulti(<M>,XPUB1/0/*,XPUB2/0/*,…,XPUBN/0/*)) and wsh(sortedmulti(<M>,XPUB1/1/*,XPUB2/1/*,…,XPUBN/1/*)) (one descriptor w/ 0 for receiving addresses and another w/ 1 for change)." Is that true? Or can I just ignore completely the trailing pathing and just do:

wsh(sortedmulti(2,[1E74CA69/48'/0'/0'/2']xpub65........................Qwg1Wd,[9F40E694/48'/0'/0'/2']xpub74hnJ........................cWoEszidc,[B5B630B5/48'/0'/2'/2']xpub6F9A........................Rb1VjK))

Hey Myles, perhaps the second question should be a separate topic, as how to get to descriptors from zpubs seems quite a bit away from whether you want separate descriptors for change and receive addresses. I edited your title to try and capture the gist of your first question. I find that trying to summarize what you are asking for rather than describing the category usually gets more interest—the categorization already happens via the tags anyway.

Thanks. I split up the questions so now it should be a little less cluttered.

The /* at he end is not mandatory, but does change the meaning, and dropping it is most probably not what you want.
Conceptually, if you have a m/48'/0'/0'/2' wallet, it means the keys your wallet uses are derived as (with m some master key):

m/48'/0'/0'/2'/0
m/48'/0'/0'/2'/1
m/48'/0'/0'/2'/2
...

In other words, it denotes a key chain consisting of multiple keys, each with their own derivation path.
The way to write that as a descriptor is as xpubM.../48'/0'/0'/2'/*, where xpubM... is the actual xpub corresponding to the master key m. In practice, you will precompute the xpub for just the derivation part m/48'/0'/0'/2' and just use xpub.../*.
You can just write "xpub...", but then you have a wallet consisting of just the single key corresponding to m/48'/0'/0'/2' itself, rather than the keys derived from that key. Similarly, you can just use xpub.../0, but then you have a wallet consisting of just the single key correspondong to m/48'/0'/0'/2'/0, which is probably just the first key you want rather than all of them.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
I can't connect to RPC from python. JSONRPCException: -342
Tryed to run this code :
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import logging
import json

logging.basicConfig()
logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG)

rpc_connection = AuthServiceProxy("http://%s:%s@127.0.0.1:18332"%('user', 'password'))
print(rpc_connection.getinfo())

with my pass and my username but I have this error:
DEBUG:BitcoinRPC:-1-> getinfo []
Traceback (most recent call last):
  File "/home/conio/Scrivania/conioclass/conio/components/provaRPC.py", line 9, in <module>
    print(rpc_connection.getinfo())
  File "/home/conio/Scrivania/conioclass/conio/components/bitcoinrpc/authproxy.py", line 139, in __call__
    response = self._get_response()
  File "/home/conio/Scrivania/conioclass/conio/components/bitcoinrpc/authproxy.py", line 187, in _get_response
    'code': -342, 'message': 'non-JSON HTTP response with \'%i %s\' from server' % (http_response.status, http_response.reason)})
bitcoinrpc.authproxy.JSONRPCException: -342: non-JSON HTTP response with '401 Unauthorized' from server
Can you help me?

Fixed... there were some problems in the bitcoin.conf file

Indeed to use bitcoinrpc, you need to set the username and password in bitcoin.conf by:
rpcauth=user:salt$hash of password

which you can generate using https://github.com/bitcoin/bitcoin/blob/master/share/rpcauth/rpcauth.py. Simply shutdown bitcoind, add this to bitcoin.conf, restart, and you'll immediately be able to run commands in python like
print(rpc_connection.getinfo())


text:
PHP Coinbase Securing Callbacks
This is example callback verification code in Ruby (https://developers.coinbase.com/docs/wallet/notifications):
CALLBACK_DIGEST = OpenSSL::Digest.new("SHA256")

def self.verify_callback(body, signature)
  return false unless callback_signing_public_key
  callback_signing_public_key.verify(CALLBACK_DIGEST, signature.unpack("m0")[0], body)
  rescue OpenSSL::PKey::RSAError, ArgumentError
  false
end

def self.callback_signing_public_key
  @@callback_signing_public_key ||= nil
  return @@callback_signing_public_key if @@callback_signing_public_key
  path = File.expand_path(File.join(File.dirname(__FILE__), 'coinbase-callback.pub'))
  @@callback_signing_public_key = OpenSSL::PKey::RSA.new(File.read(path))
end

How can I do this in PHP ?

Asking for someone to port code for you isn't a very good question.  Perhaps you should be more specific in your question about the parts of the code you don't understand.


text:
Spending transaction with custom output
I've recently entered the bitcoin arena, and bitcoinj was my tool choice. Experimenting on regression test mode, I was able to create the following custom transaction. It has a modified locking script and would need a modified unlocking, input, script.
 //Sender: sig pubk [dup() hash() pubk equ() chksig() OP_VERIFY() match_me eqal()]
 //Receiver: matcher sig pubk [dup() hash() pubk equ() chksig()]

 Script locking = new ScriptBuilder()
      .op(OP_DUP)
      .op(OP_HASH160)
      .data(address3.getHash160())
      .op(OP_EQUALVERIFY).op(OP_CHECKSIG)
      .op(OP_VERIFY)/*gets rid of the true left by previous checksig*/
      .data(match_me)/*32bytes to be matched in unlocking script*/
      .op(OP_EQUAL)/*checks the equality of match_me with one provided by receiver*/
      .build();

 Transaction contract = new Transaction(params);

 contract.addOutput(COIN.multiply(25), locking);
 SendRequest req = SendRequest.forTx(contract);
 wallet2.wallet().completeTx(req);
 wallet2.peerGroup().broadcastTransaction(req.tx);

Here, I'm trying to create this transaction that won't be spent until the receiver provides data that matches 'match_me'. The transaction half successfully spends the coins from the sender's wallet, subtracting 25 BTC from wallet2. However, wallet3 was still empty even after generating a new block.
 Transaction:
   bd52d8ef024715096b5177d581121122dc1ce9f8925c105a496bb290691ba1a7
   updated: 2016-10-02T23:19:14Z
      in   PUSHDATA(72)     [3045022100f5664de61bd0c9576d7dd2aaf98f2ba4e60c1013e55a36e62bf1d47c38a0fb5c02206872b35821f05069df5d2302dadc55011e6e6d7569e2e46c655deb9265390f3f01] PUSHDATA(33)[035562c04ff3ddb5a8ba566f4cd84c3e47478997ab8730bd923a4260fc9dfe246e] 50.00 BTC
      outpoint:7738e333b27700e835d3c118444d9f2181033c8d796ca116c66d795140ad64df:1 hash160:67d4ea4c50e80497380b7eb2f901664dc341db4b
 out  DUP HASH160 PUSHDATA(20)[d713cf366138ad0d0aac8c148ca724c18a8c4e4d] EQUALVERIFY CHECKSIG VERIFY PUSHDATA(16)[e04fd020ea3a6910a2d808002b30309d] EQUAL 25.00 BTC
 out  DUP HASH160 PUSHDATA(20)[2515ad4a14c15cc363796684149fd23ae1c3146e] EQUALVERIFY CHECKSIG 24.999877 BTC
 fee  0.00050204 BTC/kB, 0.000123 BTC for 245 bytes
 prps USER_PAYMENT

I speculate that it could be the case that wallet3 doesn't recognize the custom transaction, so it doesn't include it in its balance. Do you think so?
If I decided to spend the transaction using the txid, how would I create the inputs to unlock it? how do I create scriptsig with (.data(matcher).data(sig).data(pubkey))?
Thank you

Typically wallets do not support spending coins with any scriptPubKey except the ones they hand out themselves (in the sense that an address is a shorthand for a particulatlr scriptPubKey).
This is for good reasons. It's impossible for wallets to scan for all possible combinations and alterations of scripts with keys they know, so it would inherently be a subset anyway. It being a subset would just create unclear expectations, as senders may wonder what exactly is permitted. Furthermore, it is not the sender's business to decide what script the receiver should accept money at.
Compare this to a real life scenario where you're asked to pay someone by slipping an envelope under their door. Instead, you take the envelope and put it under their doormat. You wouldn't expect this to be a fulfillment of the payment either.


text:
What is the first Deterministic BIP39 Wallet released?
I'm studying the BIP39 and the seed phrase.
I can read this doc (https://en.bitcoin.it/wiki/BIP_0039) and I can find Created: 2013-09-10.
In bitcoin talk I can read this article (https://bitcointalk.org/index.php?topic=19137) with date June 18, 2011
I can find this post about Electrum release, https://bitcointalk.org/index.php?topic=100502.0 but i'ts just a seed not a seedphrase (or I mistake about it?)
So When did the first Wallet (and which one) implement the BIP39?
Or when the user started to use it to store his keys?

The bitcointalk post you link to was the original idea for deterministic wallets. It was adopted in the Armory wallet, and later a (different) scheme was standardized as BIP32 (disclaimer: I'm the author). BIP39 came even later and proposed replacing BIP32's seed key with a seed phrase. I don't know which wallets first implemented BIP32 or BIP39, but I wanted to make it clear that currently adopted standards had several independent components, developed by different people, spread over several years.

thanks @PieterWuille. So we could say that the Seed phrase came from 2013-09-10, and we could say that after that date a wallet could implement it. I mean the 2013-sept-10 is the release of that.
My questoin is, what is the first software wallet adopted the BIP39? in which date?

Yes, I understand the question - I don't know the answer to that. I just wanted to give some background here.

thanks for your answer Pieter very kind


text:
Stripped segwit data
I have two client Bitcoin, 0.17.0 and 0.12.0 and I want to see the difference between the same transaction.
0.17 has segwit, 0.12 doesn't have.
If I do that RPC call in 0.17.0
/bin/bitcoin-cli -datadir=./datadir getrawtransaction 6b6d286189a73d1fde6710cf7d168d0414e12d7a71e156e538e101ddc05f247a true

I can see the transaction in detail.
If I repeat the same call in 0.12 I can see the same result.
I expected that the node (0.12) stripped field like txinwitness
I use the same datadir for each node.
Why I can see this result inside vin
"scriptSig": {
        "asm": "001458f0440b4c57e6f537f519f2e991e7ee1b7bae36",
        "hex": "16001458f0440b4c57e6f537f519f2e991e7ee1b7bae36"
      },

What is 001458f0440b4c57e6f537f519f2e991e7ee1b7bae36?
Another question, how can I find a P2WPKH transaction?
-- Update --
I try to add rpcserialversion=0 in one node, and when I use getrawtransaction I can see the hex without segwit elements.
I can see in wiki

-rpcserialversion   Sets the serialization of raw transaction or block
  hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default:
  1)

In fact if I use verbose I can see txinwitness.
txinwitness is stripped in node legacy?

I don't have all the version numbers in my head anymore, but you may need to go even older. Core actually implemented segwit fully for more than a year before it got activated.

@Jannes https://bitcoin.org/en/release/v0.13.1 this is the release with segwit.

That's when the soft fork was introduced, but I'm fairly confident earlier versions were already prepared to accept and parse segwit blocks. That was done on purpose so people are not forced to update once segwit got activated.

@Jannes thanks for your reply, I'm trying to download older by the links are broken

0.13.0 contained code for segwit but not the activation code. 0.12.0 does not have segwit. However, you should not be using the same datadir between 0.17 and 0.12. In fact, the same datadir should not work and should cause 0.12 to error on startup due to database changes that happened in 0.15. The fact that it doesn't indicates that you are not actually running 0.12 when you think you are.


text:
Sequence valid before time
I'm studying sequence, and I set a transaction valid after 512 seconds.
First of all I use regtest and I start from clean blockchain, after that I mine 114 blocks.
At this point miner creates a transaction and tries to send it
My decode transaction
{
  "txid": "59ff4adafb47a5b22c6434af38f6e138c9008356778ed8b308c48029d7d4032f",
  "hash": "1bef48f96d18f1c78021b7e4b0a7d5285f6f7d2cc8c7adc31671820e367c3d70",
  "version": 2,
  "size": 191,
  "vsize": 110,
  "weight": 437,
  "locktime": 0,
  "vin": [
    {
      "txid": "88fb1408675c774c36692f170c6122af49cab7a5bab336272f0e4d8c0ef8c89a",
      "vout": 0,
      "scriptSig": {
        "asm": "",
        "hex": ""
      },
      "txinwitness": [
        "3044022070b753c99e2b6d241fd8a4ebe26f53644ef3eea58fff743e51f7a69e1ee7a99602204cbe9a60fc25be24baa3e4613f27a3e51df4a285174e001b62de18e1da2e42fd01",
        "03494041191fd2b02579fd49877755e55d9d451a37c6d0bbe04aab8ef507a78b19"
      ],
      "sequence": 4194305
    }
  ],
  "vout": [
    {
      "value": 49.99100000,
      "n": 0,
      "scriptPubKey": {
        "asm": "0 18363770025baac1ebdb99a948eab2776d9568ae",
        "hex": "001418363770025baac1ebdb99a948eab2776d9568ae",
        "reqSigs": 1,
        "type": "witness_v0_keyhash",
        "addresses": [
          "bcrt1qrqmrwuqztw4vr67mnx55364jwake269w8hl5fe"
        ]
      }
    }
  ]
}

I Give an error when I try to use sendrawtransaction
error code: -26
error message:
non-BIP68-final (code 64)

And it's correct because my UTXO (88fb1408675c774c36692f170c6122af49cab7a5bab336272f0e4d8c0ef8c89a) come from the block with height 2 and 113 confirmations, and its median time is 1590276467 (2020-05-24 01:27:47 CET/CEST) and My transaction is valid after 512 seconds (Date:2020-05-24 01:41:23 CET/CEST) and the best block has that value 2020-05-24 01:28:06 CET/CEST (it's not useful)
Now, If I create another transaction with the TXID comes from block with height 1 and 114 confirmations it works, I can send it.
Below my transaction and details.
{
  "txid": "f98d3ef70ca2c9d797bf7fff2e96e07f5ba10a280186a2132c6a902eebcab31e",
  "hash": "5776ad750fe759411a1ed5aa10e759b33e52b2935555d90b997fa788c9e25405",
  "version": 2,
  "size": 191,
  "vsize": 110,
  "weight": 437,
  "locktime": 0,
  "vin": [
    {
      "txid": "e1ee4602a78ab4f5f58705a75405d2f223307989950e1cbe03a4518cf23b7914",
      "vout": 0,
      "scriptSig": {
        "asm": "",
        "hex": ""
      },
      "txinwitness": [
        "304402200641ef29e3f0c8ef0c55dbb4a86a752e3655dd0c928c4e2e6659d3beeaf3f3870220026821b9ba043894cb20c7d7a378eaae76f56400755bf412f8ab1524a9a238b301",
        "03494041191fd2b02579fd49877755e55d9d451a37c6d0bbe04aab8ef507a78b19"
      ],
      "sequence": 4194305
    }
  ],
  "vout": [
    {
      "value": 49.99100000,
      "n": 0,
      "scriptPubKey": {
        "asm": "0 18363770025baac1ebdb99a948eab2776d9568ae",
        "hex": "001418363770025baac1ebdb99a948eab2776d9568ae",
        "reqSigs": 1,
        "type": "witness_v0_keyhash",
        "addresses": [
          "bcrt1qrqmrwuqztw4vr67mnx55364jwake269w8hl5fe"
        ]
      }
    }
  ]
}

The median time of block 1 and 114 confirmations is 1590276486 (2020-05-24 01:28:06 CET/CEST) and my transaction should be valid after 512 seconds (2020-05-24 01:45:05 CET/CEST), and my best block median time is 2020-05-24 01:28:06 CET/CEST
Below, the details of block 2 with 114 confirmations
{
  "hash": "5f769f610f29057577611868a660b353bea06e51d94905f3dbf7fb93e60a3d30",
  "confirmations": 1,
  "strippedsize": 214,
  "size": 250,
  "weight": 892,
  "height": 114,
  "version": 536870912,
  "versionHex": "20000000",
  "merkleroot": "1699f1cebdde9f4da1211f948f2ec194f7820fcfbab80c93bb5ea486e6837be7",
  "tx": [
    "1699f1cebdde9f4da1211f948f2ec194f7820fcfbab80c93bb5ea486e6837be7"
  ],
  "time": 1590276487,
  "mediantime": 1590276486,
  "nonce": 0,
  "bits": "207fffff",
  "difficulty": 4.656542373906925e-10,
  "chainwork": "00000000000000000000000000000000000000000000000000000000000000e6",
  "nTx": 1,
  "previousblockhash": "36f373a49886a31eff05ff8de39722f589cff103bed47715dd697d14350539ce"
}

Now, I know the sequence (00000000010000000000000000000001) is checked on median time of UTXO's block, But block 2 (with 114 confirmations) and block 3 (with 113 confirmations) are very similar and very close, and I don't understand why with block height 2 I'm able to send the transaction.

I just see that BIP68 states
    // Time-based relative lock-times are measured from the
    // smallest allowed timestamp of the block containing the
    // txout being spent, which is the median time past of the
    // block prior.

so, the relative timelocks for UTXOs in the block 1 (which 114 confirmations) are verified against the mediantime of the prior block, so the block with height 0 in regtest has a hardcoded median time to 2011 ("mediantime": 1296688602, 2011-02-03 00:16:42 CET/CEST)


text:
Generate P2SH-P2WSH
I want to generate P2SH-P2WSH with script P2PKH.
My public key is    027712968e8f2f9dfa79abe10940a3d915a0c95a0b97750881e6201acf2b66da97

SHA256 and RIPEMD160 of Public key
 ---------- Witness Script ---------
#OP_DUP OP_HASH160 <PubKHash> OP_EQUALVERIFY OP_CHECKSIG
76a914651554088a30217e6d0261cce1634e9d90b03f7088AC

 ---------- scripthash ---------
#SHA 256 of Witness script
1eb6c6c3ad4e395e66e3521c23486863fe363939db88c38a3c6461cb66f80254

  ---------- Redeeem script ---------
#add OP_0 (0x0020{32-byte scripthash})
00201eb6c6c3ad4e395e66e3521c23486863fe363939db88c38a3c6461cb66f80254

  ---------- SCRIPTPUBKEY ---------
#RIPEMD160(redeem script)
#OP_HASH160 hash160(redeemScript) OP_EQUAL
A9149fbb6d60a6d26f67b9673334c3863cdec224169787

ADDRESS:
#C4A9149fbb6d60a6d26f67b9673334c3863cdec224169787 base58 cecksum
2N7ooxTaU8FRgfTrhYn3FjwUcFqeNRvRU5k

Now I want to try to spend form this address.
bitcoin-cli signrawtransactionwithkey $TX_DATA '["'$PK'"]' '[{"txid":"'$TXID'","vout":'$VOUT',"redeemScript":"'$REDEEMSCRIPT'","scriptPubKey":"'$SCRIPTPUBKEY'","witnessScript":"'$WITNESSCRIPT'","amount":"'$TOTAL_UTXO_AMOUNT'"}]'

I receive this error

redeemScript does not correspond to witnessScript

Are you trying to build a backward-compatible segwit P2WPKH address (P2SH-P2WPKH)?

I think you have an extra "00" in your redeem script before the {32-byte scripthash}. The serialized version of the redeem script must be: (0x220020{32-byte-hash}). The firs "22" corresponds to the 34 (in hex) of the length of the following script. The next "00" corresponds to the OP_0. The next "20" represents the length of the hash (32 bytes in hex). So the "00" represents the OP_0, but you are repeating this item in your script.

@OscarSerna thanks to reply I try to add 22, it's my redeem script 2200200c3727796d979c4d9ac585736a33dd6a976a3f290e96a6cc6ddac993ee6b4c8b but I have the same problem

are u still working on this?

At the time this question was asked, this issue was the result of a bug in Bitcoin Core. It was fixed in PR #18484 and is available in Bitcoin Core 0.20+.

Hashing Redeeem script to use in SCRIPTPUBKEY uses the wrong hash algorithm.
RIPEMD160(Redscript) = f23bde7eee22aabca28164cb4b8a977834e5441b but we want  HASH160 which is
RIPEMD160(SHA256(Redscript)) = c39f7f611a844bd7118dac9166fa9c1398676c30
(I used this script to calculate it)

hey thanks :), I updated my question with you suggest. but I have the same problem. the values are differents because I have a script to generate my address

You can use bitcoinjs Lib.
function generateAddress('P2WSH', publicKeyHash, network)   {

    return redeemScript = bitcoin.script.witnessPubKeyHash.output.encode(publicKeyHash);
                let redeemScriptHash = bitcoin.script.scriptHash.output.encode(bitcoin.crypto.hash160(redeemScript));
                address = bitcoin.address.fromOutputScript(redeemScriptHash, network);
    }
        // create new random key pair of eliptic curves
            let keyPair = bitcoin.ECPair.makeRandom({network: network});

            // public key buffer
            let publicKeyBuffer = keyPair.getPublicKeyBuffer();

            // public key hash
            let publicKeyHash = bitcoin.crypto.hash160(publicKeyBuffer);

            // generate Address
            let address = generateAddress('P2WSH', publicKeyHash, network);

            // return wallet
            let wallet = {
              "address": address,
              "privateKey": keyPair.toWIF()
            };

Thanks @Hamza, I don't want use external library. I want to do all the hard work :P

Ohh i see. Please share with us as well when you get it :)


text:
How to send portion of funds from a private key programmatically?
I'm building an app and one of my features is being able to scan a bitcoin private key and then send a portion of its funds to another address. How can I do something like this in javascript or php? Do I need to run my own Bitcoin server?
Is there an example script I can use where I can just plug in a private key?

You can either use your own bitcoind server or you can use a 3rd party API service.
Let's do a few examples of what you are asking.
I'll use short fake addresses and private keys as examples to make things easy.
PHP with a bitcoind server
<?php
require("easybitcoin.php");
$bitcoin = new Bitcoin("username", "somepassword");

//add the private key (label, key)
$import = bitcoin->importprivkey("5KL3cN..SOME_PRIVATE_KEY", "Satoshi1");
?>

What we did here was import a private key and give it a specific unique label.  This part might take a while as your node will need to rescan as you added a new private key and it needs to check for transactions.
Once the node is rescanned you can send the funds.
<?
require("easybitcoin.php");
$bitcoin = new Bitcoin("username", "somepassword");

//send the funds from the Satoshi1 account/label
$send = $bitcoin->$bitcoin->sendfrom("Satoshi1","1receivingAddress", 0.5);
echo $send ? $send : "Oops an error: ".$bitcoin->error;
?>

What we did above was use the sendfrom() JSON RPC command to send 0.5BTC from the account/label Satoshi1 to the 1receivingAddress. If successful it will respond with the transaction ID, or if an error it will print out the error.
This is just the code, you'll still need to set your VPS with bitcoind or you can run a node on your home computer and experiment locally using something like xampp.
PHP with a 3rd party API
Here's an example with blockchain.info wallet API. You can import the private key using their create wallet utility, and then later send from that specific address.
$private = "5KL3cN..SOME_PRIVATE_KEY";
$url = "http://127.0.0.1:3030/merchant/YOUR-GUID/create?password=YOUR-PASSWORD&api_code=YOUR-API-CODE&priv=".$private;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //change to true if your host can verify SSL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$ccc = curl_exec($ch);
$json = json_decode($ccc, true);
echo "
";
var_dump($json);
echo "
";

Then once created you can send from that specific new address that was imported.
$from = "1fromAddress";
$to = "1receivingAddress";
$url = "http://127.0.0.1:3030/merchant/YOUR-GUID/payment?password=YOUR-PASSWORD&api_code=YOUR-API-CODE&from=".$from."&amount=1000000&to=".$to;
//amounts are in satoshi so 1000000 is 0.01BTC
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$ccc = curl_exec($ch);
$json = json_decode($ccc, true);
echo "
";
var_dump($json);
echo "
";

If you need help setting up bitcoind or blockchain.info's wallet API I suggest you check out my tutorials on youtube. The hardest part with the 3rd party route is getting an API key; I hear blockchain.info has been strict with these lately.
bitcoind server method: https://www.youtube.com/watch?v=cMM-t7azzJE
blockchain.info 3rd party method: https://www.youtube.com/watch?v=X8jsaf4sEgs

im assuming this is the version i would need to download and run? https://bitcoin.org/en/download -- i just want to make sure. thanks for the answer!

Also can this be done with other wallets that doesnt require downloading the entire blockchain like bitcoin core?

The bitcoind version would require you to download and run bitcoin core. You can prune it though, if you are concerned with hard-drive space and still have full wallet functionality.

but the thing is i dont want it to store the private keys. is there a service for such a thing? or I would just have to remove it from these apps manually? What command would one use then?


text:
Please explain this weird bitcoin transaction
I am an EVM blockchain engineer and I started learning Bitcoin few days ago.
this is my friend's address of bitcoin wallet: bc1pfatr7dvkz65y6p6xxv84anesttxc7q9etez8em5uyvll5kk8atpqrx3r2s
and what makes me confused is a transaction in his history. https://mempool.space/address/bc1pfatr7dvkz65y6p6xxv84anesttxc7q9etez8em5uyvll5kk8atpqrx3r2s

the very first transaction is understandable.
there was no transactions before first transaction and bc1q7pcfjas8swacpwnmm5d4s679jffn3lawkm89kv sent some amount of BTC to this wallet. (It's okay)
but the next transaction is strange.

1.where these inputs come from?
BTW please explain this output as well.
2. why there are two outputs that is same as wallet address?

3. and what is the meaning of this green button?

I am looking forward to kind help of community members.
please make me clarify this problem.
Thanks in advance.

Related topic: https://bitcoin.stackexchange.com/q/96822/5406

1.where these inputs come from?
One single Bitcoin transaction can have multiple inputs and multiple outputs. Multiple Bitcoin from different addresses can be spent as inputs in one single transaction, and one single transaction can send Bitcoin to multiple addresses(outputs).
2. why there are two outputs that is same as wallet address?
It's allowed to have two outputs with the same address in single transaction.
3. and what is the meaning of this green button?
It means the output Bitcoin is not yet spent, so it's UTXO(Unspent Transaction Output).


text:
Is Testnet3 Addresses Support Segwit P2WSH P2WPKH transactions?

How Do I Know if My Bitcoin Address Is Segwit?

"Today, many Bitcoin wallets support SegWit by default. Bitcoin SegWit addresses typically start with a “3” or “bc1”.

Addresses starting with “3” are known as Pay to Script Hash (P2SH), which supports SegWit.
Addresses that begin with “bc1” are Bech32 addresses and represent native SegWit addresses that fully utilize the SegWit efficiency improvements.

If your address starts with “1”, it’s a legacy address and does not support SegWit."
My btc address "mguwz9PVtTrp11hzvp1atGBtTcFRvoHBCh" is this.
Does my btc address support segwit transactions?

It's Pay to Public Key Hash(P2PKH) testnet address, which doesn't support SegWit.
P2PKH address(legacy) which starts with “1”, starts with either "m" or "n" on testnet.
You can find the list of the prefix for address here.


text:
Is there a way to salvage the old mining software originally included in bitcoin core to mine with just a standalone computer - no asic?
I'm trying to figure out how to use mining software on my computer with a full node.
The API's seem configurable to allow my cpu to mine, there's just no longer direct support for such a method anymore, to my understanding.
I know I'll basically have a 1 in 100 Trillion odds of mining each block, but I still want to configure the option to turn mining on/off with a auxiliary system that does the final hashing when given all the header info.
What would I need to do to set up some software that does the basic functions of block construction and hashing, and then uses the api to submit the blocks?
I'm curious if downloading and transferring over some of the .12 bitcoin core software would work.
I'm not concerned with profit, or any return, I just want to know how to set up mining software without specific hardware (other than built in CPU).
I just want it to be able to do these two functions:

input address -> use bitcoin-cli to output block header & target

input success header -> use bitcoin-cli to submit block to networkhash

If that's something that already exits I don't want to recode it, but if it's not possible to find something that does that I'll just have to code it I guess which is fine.

This question is similar to: In the ASIC-age, is it worth starting mining Bitcoin at home?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.

Given the meager odds, would mining some blocks on e.g. Testnet 4 sate your curiosity?

@VojtěchStrnad Hi, Thanks for the response. The difference I'd say is that I'm not curious about the profitability or anything with it. I'm not trying to make money, just run a computer solo node in which I can also enable mining. I'm already set on it, I just want to find out how to do without a separate mining device, solo from the laptop, with portability for mining attachment.

@Murch I'm afraid it's not just about the curiosity element. More than anything, I want software that's specialized just to the first function of receiving input (previous header, array of transaction requests, miner address) and generating output (hash-ready header) and a second function of receiving input (complete valid header) and then submitting a block to the network.

Bitcoin Core still includes a bit of mining code. It's not as optimized as the code once used for actual CPU mining because it's meant to be used on regtest where the mining difficulty is permanently low, but nothing stops you from using it on mainnet, and since finding a block with a CPU is basically impossible today even with optimized code it doesn't really matter.
All you need to do is run the command generatetoaddress with your own address. By default it will try 1,000,000 different nonces before stopping, but you can set it to more. If my numbers are correct, letting it run for a few hours on a reasonably new CPU should be enough to get you to a 1 in 100 trillion chance of finding a block.

I got the same numbers too. CPU is capable of something like 7 MH/s, so yeah, 1 in 100 trillian

I'll try generatetoaddress let me see if it does what I'm looking for.

It will do nothing, but since you're looking to mine on a CPU that's really all you can expect.


text:
Importaddress and migrate to descriptor
I created a script for studying purposes, generating a private key, a public key, and a P2SH address with a redeem script and RIPEMD160. I stored the address string in address_P2SH.txt.
I updated Bitcoin Core to version 26, and since version 0.21, Bitcoin uses Descriptor wallets. Now, I can't use importaddress because, by default, createwallet uses descriptors.
ADDR_P2SH=`cat address_P2SH.txt`
bitcoin-cli importaddress $ADDR_P2SH

I know I can use descriptor=false during createwallet, but I'd like to know if I can migrate my "external" address to a descriptor and sign my transaction with signrawtransactionwithwallet. If I'm not mistaken, I can't use signrawtransactionwithkey anymore because the descriptor doesn't allow getting the private key, only the master private key, even if I have the private key from my external address.
Update
The redeem script is a P2PKH SCRIPT="76a9"$PBLENGTH$PBH"88AC". I presume that the logic for other kinds of scripts is the same.
second Update
I followed the steps of @Pieter Wuille
bitcoin-cli getdescriptorinfo "sh(pkh($(cat compressed_private_key_WIF_1.txt)))"

and I got
{
  "descriptor": "sh(pkh(0233e11f2a33d480d4fa1bcb7a0e118ea56d6511a21735e01c00182e924c5a8efc))#cx4xdav6",
  "checksum": "e2yjqzgh",
  "isrange": false,
  "issolvable": true,
  "hasprivatekeys": true
}

then
 bitcoin-cli importdescriptors '[{ "desc": "sh(pkh(0233e11f2a33d480d4fa1bcb7a0e118ea56d6511a21735e01c00182e924c5a8efc))#cx4xdav6", "timestamp": "now", "internal": true }]'
[
  {
    "success": false,
    "error": {
      "code": -4,
      "message": "Cannot import descriptor without private keys to a wallet with private keys enabled"
    }
  }
]

Third update
Thanks to Peter I can import the address
CHECKSUM=$(bitcoin-cli getdescriptorinfo "sh(pkh($(cat compressed_private_key_WIF_1.txt)))" | jq -r .checksum)

bitcoin-cli importdescriptors '[{ "desc": "sh(pkh('$(cat compressed_private_key_WIF_1.txt)'))#'"$CHECKSUM"'", "timestamp": "now", "internal": true }]'

What kind of script is the P2SH redeemScript? With just an address all you can do is watch. If you want to participate in signing, you'll need a descriptor that describes how the address is constructed. I can't advise on that without knowing what the script is.

you are right, I Updated my question

If all you have is an address that you want to watch, you can use an addr(ADDR) descriptor (with ADDR replaced with your actual address). Importing that will make a descriptor wallet treat the address as its own, list its transactions, and use it in balance calculations.
If you want to also participate in signing, you'll need to provide more detail about its construction.
In your case, we're talking about a P2PKH-in-P2SH script, for which the descriptor would be sh(pkh(KEY)) (sh is for P2SH, pkh is for P2PKH), where KEY can either be a hex pubkey, a WIF privkey, an xpub with derivation path, or an xprv with derivation path.
See the descriptors documentation for how to write ones for other types of scripts, but in very short, the single-key constructions I can come up with:

pk(KEY) for P2PK
pkh(KEY) for P2PKH
wpkh(KEY) for P2WPKH
tr(KEY) for P2TR (with KEY as internal key)
sh(pk(KEY)) for P2SH-P2PK
sh(pkh(KEY)) for P2SH-P2PKH
sh(wpkh(KEY)) for P2SH-P2WPKH
wsh(pk(KEY)) for P2WSH-P2PK
wsh(pkh(KEY)) for P2WSH-P2PKH
sh(wsh(pk(KEY))) for P2SH-P2WSH-P2PK
sh(wsh(pkh(KEY))) for P2SH-P2WSH-P2PKH

It's hopefully obvious that I don't recommend any but the first few in this list, but it can be fun to play around with the ability to compose.
Note that the importdescriptors call requires descriptors that include a checksum. The checksum can be calculated using the getdescriptorinfo RPC.

I'm using P2SH-P2PKH because I created some examples for my study notes, and now I want to adjust them if possible. I also have examples for P2SH-P2PK and P2WPKH.

I updated again the answer with your steps

@monkeyUser The descriptor field in the getdescriptorinfo output is the normalized descriptor (which excludes private key material) for your input (note that it replaced your WIF key with a hex pubkey). If you want to import private key material too, you need to use the original (the checksum field reports the checksum for your original descriptor).

Thanks for your time and for new edited answer


text:
Calculate mnemonic code from terminal
I want to replicate mnemonic code with terminal.
the steps are:

Create a random sequence (entropy) of 128 to 256 bits.
Create a checksum of the random sequence by taking the first (entropy- length/32) bits of its SHA256 hash.
Add the checksum to the end of the random sequence.
Divide the sequence into sections of 11 bits.
Map each 11-bit value to a word from the predefined dictionary of 2048 words.
The mnemonic code is the sequence of words.

I can see this image

And I take this entropy
0c1e24e5917779d297e14d45f14e1a1a

If I follow the image, I create the checksum
printf 0c1e24e5917779d297e14d45f14e1a1a | xxd -r -p | sha256sum -b

result
76e57a90f93135e97ce700a9e79196ba46315d65e696d0a4518270a8de3e80e4

Then take 4 bits (0,5 byte => 1 char ) and append to my entropy with this result:
0c1e24e5917779d297e14d45f14e1a1a7

Now I have 132 bits And I have to split in 12 segments of 11 bits each
I try to convert in base 2
 echo "ibase=16; obase=2; 0C1E24E5917779D297E14D45F14E1A1A7" | bc

11000001111000100100111001011001000101110111011110011101001010010111111000010100110101000101111100010100111000011010000110100111

But the result is not correct, If I put that entropy in https://iancoleman.io/bip39/#entropy-notes I can see that result
00001100000 11110001001 00111001011 00100010111 01110111100 11101001010 01011111100 00101001101 01000101111 10001010011 10000110100 0011010

But I don't understand How can I obtain that
00001100000 = 96 = army

See the dictionary: https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt 00001100000=96=army, 11110001001=1929=van, etc. Checksum of 0111 (7) seems to be correct as well. Do you get a different binary?

@JamesC. Yes update my question

Take a look at one of the answers under https://bitcoin.stackexchange.com/questions/83883/manually-generating-seed-for-trezor-t/83923#83923.

Your binary (which includes the 4 checksum bits 0111, or 7) has the leading null's removed.
(0000)1100000 11110001001 00111001011 00100010111 01110111100 11101001010 01011111100 00101001101 01000101111 10001010011 10000110100 00110100111
Which is identical to the binary (without checksum bits 0111) from the web tool:
00001100000 11110001001 00111001011 00100010111 01110111100 11101001010 01011111100 00101001101 01000101111 10001010011 10000110100 0011010....
(Note the missing checksum bits .... at the end)

I don't understand sorry. My checksum is 7. 7 in binary is 111 echo "ibase=16; obase=2; 7" | bc.

If I do echo "ibase=16; obase=2; 0C1E24E5917779D297E14D45F14E1A1A" | bcwithout seven I have 1100000111100010010011100101100100010111011101111001110100101001011111100001010011010100010111110001010011100001101000011010
Why I have to add 0000 to the beginning?

Yes, 111 = 0111, the leading zeros are always clipped by your command line tool. But you need to maintain all leading bits, even if they are nulls, because we need exact multiples of 11 for the mnemonic key word.

The 0 in 0C1E24E5917779D297E14D45F14E1A1A is 0000 bits, but these are clipped by the encoding tool. The tool preserves the value of the hex, because the leading null's do not contribute to the value, but we need a fixed-width binary encoding so we always have multiples of 11 bits for the words.

If your entropy were 000E24E5917779D297E14D45F14E1A1A, it would clip the 12 leading 0 bits.

I'm stupid, 7 in base 2 is 0111 you are right ! But I don't understand why 0 is 0000 bits and I ave to add before my binary sorry

Let us continue this discussion in chat.

I have to add padding maybe https://pastebin.com/jUCLmsX8

1hex is 0001bits. The 3 null bits are clipped by your tool.

2hex is 0010bits. The 2 null bits are clipped ...

How many leading nulls are clipped depends on the first hex character.


text:
Can I spend/transfer bitcoins directly from cold storage?
From reading previous articles I understand that you can receive bitcoins to an address even if your wallet is in cold storage because the bitcoins sent to this address is recorded by someone on the block chain. Is this correct? and who is this someone?
Now If I have bitcoins stored in an offline laptop (I believe this is called cold storage) is it possible I can create some sort of QR code with my offline laptop and just have my mobile Android bitcoin wallet snap the QR code and wallah the bitcoins are transferred from cold storage to hot? Do I also need to enter my private key to enable this?

What you have to understand is that bitcoins only exist in the blockchain. They do not exist in your wallet, either online or offline. All that contains is your public and private keys that allow you to make transactions on the blockchain. You do not transfer bitcoins anywhere when you move them to cold storage, they still only exist as transactions on the blockchain. The wallet cold, or hot, only contains the keys that let you authorize transactions on the blockchain to "spend" those coins.

Thanks for that, still trying to build my fundamental knowledge so that does help unconfuse me! One more question if you have time, can I authorise transactions on the block chain from my private keys stored in a cold wallet via a hot wallet that is connected/online to the block chain? Thanks again

You can generate a signed transaction on an offline machine as long as it knows what to sign and has the private key. The tx can then be moved to an internet connected machine for submission. The problem is the "know what to sign" bit, a Bitcoin transaction references the output of a previous transaction so that information would need to be fed to the cold wallet. Common practice is to create a new cold storage key and import the old key(s) into a regular wallet where the funds are immediately sent from the old cold address(es) to where they are need and the change to the new cold address.

Every bitcoin and bitcoin transaction is stored in the blockchain which is online, distributed and known by every full bitcoin node.
What you have on your pc are private keys.   As long as you have this private key, you can sign any transaction which matches the corresponding public key.
An offline, or cold-wallet is a wallet that is not connected to the internet, so nobody can ever figure out your private keys by hacking you - the keys aren't connected to the internet.
Spending coins is basically signing (with your private key) that you wish to yield the control of your coins to someone else.
To sign this message, you will usually need a pc which is online to create the message to sign, and has a copy of the private key.  It also needs to be online to send that signed message.
So unless you have a way to transfer the message to sign to and from a completly offline computer, you will always have to bring your wallet online to spend your coins...

Thanks Peter that was a very logical and concise explanations, thanks

The system you describe is similar to the way Armory suggests you use it. You can sign a transaction offline, then transfer that signature to an online computer and broadcast it. Your private key has never been on an internet-connected computer, but your transaction has.
That said, be very careful spending from a cold storage address. There are many possible pitfalls that all have to do with the way the network/clients handle "change". Generally you'd be better off sweeping the balance into another address, doing what you want with it, and then using a different cold storage address to protect your funds again.
If you choose to use the first method, I'd suggest you read more about how change is handled.

'Spending' doesn't have to involve signing.
If your sole copy of a key is on a piece of paper you could 'spend' it by giving it to someone else. They'd probably want to secure it by signing it to a new address before you regenerate the key using your master key, but in a trust-based transaction you could call it spending.


text:
Looking for a generic wallet solution with focus on security
As above, I am looking for a coin agnostic wallet solution with all basic functionalities of a wallet, particularly multi-sig. Primary coin focus is on bitcoin, bitcoin cash, bitcoin gold, ethereum, litecoin and ripple. ICO is not part of consideration and language is not important.
Anyone has done a comparison to share please.
Thank you.

There are hundreds of different types of cryptocurrency, so I'm voting to close this as too broad.

Thank you for comment. I have edited to make it more specific as suggested

Good edit; I've nominated the question to be re-opened. I'm not sure if such a wallet exists (except maybe as an e-wallet in an exchange), so I'll be interested to see the answer :-)


text:
Fedimint for Privacy
I heard from a podcast that a way to enforce privacy in your coins while DCA'ing could be sending your lightning BTC to a fedimint, and then send it to on-chain. What privacy properties would one be able to expect from this procedure vs coinjoin/mixing?

"Is this the new norm?" is probably a matter of opinion or research. Given that we try to focus on facts and expertise here, your question might be a better fit if you were aiming for something more answerable, e.g. "What privacy properties would one be able to expect from this procedure?"

Thanks! I updated the question accordingly


text:
How to determine the input stack format for a Miniscript script?
Is there an exact "calling convention" produced when you compile a policy? I am guessing this information must be available somewhere since the compiler has to perform its own validity analysis. I would just like to know exactly what I have to put in the witness stack to unlock the output without trying to figure it out from the script.

Yes. This is one of the main purposes of Miniscript to make it possible to construct witnesses in a general yet safe manner. The satisfaction table in the Miniscript BIP defines the witness stack element(s) to satisfy each fragment.


text:
What is equivalent to walletcreatefundedpsbt but with an arbitrary funding wallet?
I'm interested in creating a swap application using HTLCs. The user connects their wallet to the frontend, places an order, and the backend matches the order with a maker and creates the HTLC transaction. The user's UTXOs are used as inputs to fund the transaction, and the single non-change output is the one with the HTLC as the unlocking script. The flow would look similar to the one depicted here:

However, I don't want the backend to have to do the coin selection and figure out which UTXOs are optimal to fund the transaction. From my understanding, normally the walletcreatefundedpsbt RPC method would do that for you, but in this case the wallet in question is the user's wallet. Is there an equivalent way I can do coin selection for someone else's wallet?

No, coin selection does not have a public API nor any RPCs to operate on arbitrary UTXO pools. The only way to use Bitcoin Core's coin selection algorithms is to create a wallet that has the relevant scripts imported so that it detects the UTXOs and can do coin selection on them.

How would one typically accomplish this then? I notice that mempool.space's GET Address UTXO endpoint does something similar:

Get the list of unspent transaction outputs associated with the address/scripthash. Available fields: txid, vout, value, and status (with the status of the funding tx).

However this would only work for a single address in the derivation sequence.


text:
How does MuSig work in real Bitcoin scenarios? Questions on communication and steps
Signature Generation

Let L = h(P1 || ... || Pn). Each participant computes the digest: ai = h(L || Pi).
Compute the aggregated public key: X̃ = Σ (ai * Pi) for i = 1, ..., n. X̃ is made public.
Each participant randomly selects ri and computes: Ri = ri * G. Each participant sends their commitment: ti = h(Ri) to all other participants.
After receiving the other n-1 commitments, each participant sends their point Ri.
After receiving the other n-1 points Ri, each participant verifies: ti = h(Ri) for all i ∈ {1, ..., n}.
Calculate the aggregated point: Rsum = R1 + ... + Rn.
Each participant computes the challenge: c = h(Rsum || X̃ || M).
Each participant calculates their partial signature: si = ri + c * di * ai mod N.Finally, compute the aggregated signature: ssum = s1 + ... + sn mod N.
The signature is the pair (Rsum, ssum).

Signature Verification
Check if:
ssum * G = Rsum + c * X̃.
Questions:

Sharing ti, Ri, and si:
How do participants send their commitments (ti), share their Ri values, and exchange partial signatures (si)? What does this process look like in practice? Is there a standard, asynchronous, and user-friendly way to manage this in software? Or do participants need to manually compute their si, sum them, and share the results back and forth?

Verification Process:
Who verifies the final signature (Rsum, ssum)? When and how does this verification happen in real-world Bitcoin use cases? Is the verification done via P2SH scripts?
And regarding the initiation of the verification process—does a participant (e.g., one of the multisig signers) who has collected all the Rsum and ssum values create the transaction from the P2SH address? Or am I misunderstanding this flow?

What Happens Without Commitments?
What could an adversary do if the commitments (ti) were not part of the protocol? What kind of attacks could occur, and how would they exploit the lack of commitments?

Have you read BIP 327, the MuSig2 spec for Bitcoin?

@PieterWuille is MuSig2 used by Bitcoin? I thought it was still a BIP.... anyway, I asked about MuSig1, not MuSig2

For all intents and purposes, the MuSig1 scheme is supplanted by the MuSig2 scheme (and the MuSig2* scheme defined in the same paper). MuSig2 only needs 2 rounds of interactions, as opposed to the 3 rounds that MuSig1 needs, at the cost of a small bandwidth and computation increase. As far as I know, no production-ready specification for MuSig1 was ever written, and nobody ever deployed MuSig1 in production.
MuSig1 and MuSig2 are multi-signature schemes, which support key aggregation compatible with Schnorr signatures. This means that it enables a group of participants to jointly produce a single Schnorr signature that is valid for an aggregate of their public keys. Verifiers do not need to know or care that the signature was constructed through MuSig; for all intents and purposes, it is a normal Schnorr signature.
The MuSig1 paper does additionally propose an Interactive Aggregated Signature (IAS) variant of the MuSig1 multi-signature scheme. In this variant, each signer can have their own message to sign, and the result is not compatible with Schnorr signatures (because the verifier needs to know all messages being signed, while Schnorr signatures only have one message). While MuSig1 (and MuSig2) can be turned into IAS schemes like this, there are simpler algorithms like BN06 that also support this.
This distinction is relevant for how these technologies can be used in Bitcoin:

Multi-signatures can be used as a cheaper, more compact, and more private replacement for Bitcoin's traditional OP_CHECKMULTISIG-based multisig(*) scripts. Instead of publishing all public keys, and all individual signatures to the blockchain at spending time, only the aggregated public key (pre-negotiated between the participants) and the aggregated multi-signature is published. Notably, this does not require integration of the scheme "in" Bitcoin, in the sense that it doesn't become part of its protocol or consensus rules. It is just something any group of wallets that want to engage in multisig-like control of funds can choose to use, without anyone else needing to be aware.

The IAS variant is potentially useful for cross-input aggregation (CISA): the idea that an entire transaction (not just a single input of a transaction) would only need a single signature, created jointly by all participants whose coins are spent by the transaction. This is typically just a single party, but may involve multiple parties in the case of CoinJoin, for example. This is distinct from the multi-signature case in multiple ways:

Each output still has its own public key(s). Instead of doing the key aggregation ahead of time when the address is decided, it is done when spending.
The set participants may not be known before spending time (e.g., in a CoinJoin they are decided on the fly).
This requires integration into Bitcoin's consensus rules. There is no way today for scripts to even observe what other inputs of the same transaction are doing. Enabling the ability to have a single signature for all of them necessarily means changing that.

I bring this distinction up because based on your comments, you seem to be under the impression that MuSig (1 or 2) needs to be integrated "into" Bitcoin, and CISA is the only application I'm aware of that actually needs something like this. Using MuSig as a replacement for multisig can be done by anyone at any time, without anyone's permission. We wouldn't even be able to tell if someone were to be using MuSig1 today on Bitcoin.

Lastly, while the "P" in BIP means "proposal", BIPs are really just the name of the documents, and process around those documents, in which specifications for Bitcoin are published. Some BIPs never make it past the point of being a proposal, but others end up being part of the protocol. In either case, it is not because something is (still) a BIP that it is or isn't "part of Bitcoin". This is up to individual software choosing to implement these proposals or not.
(*) Note that "multisig" in Bitcoin context means "k-of-n spending policy" (where k may be less than n), while multi-signatures in the cryptography context means "compact n-of-n signature", while compact k-of-n signatures are known as threshold signatures. There is work as well on Bitcoin-compatible threshold signatures, such a FROST.

As for your questions:

Sharing ti, Ri, and si: How do participants send their commitments (ti), share their Ri values, and exchange partial signatures (si)? What does this process look like in practice? Is there a standard, asynchronous, and user-friendly way to manage this in software? Or do participants need to manually compute their si, sum them, and share the results back and forth?

For MuSig2 (itself specified for Bitcoin in BIP327), there is BIP373 which specifies MuSig2-specific fields for the PSBT (partially signed Bitcoin transaction) format. Multisig participants can then exchange PSBT files with each other.
Beyond that, expect that MuSig2 will be integrated into more ad-hoc protocols.
Parties can aggregate the partial nonces received from other parties themselves, or have one coordinator do that for them. A dishonest coordinator can only result in an invalid signature; they can't cause forgeries or key leaks.

Verification Process: Who verifies the final signature (Rsum, ssum)? When and how does this verification happen in real-world Bitcoin use cases? Is the verification done via P2SH scripts?

The final signature is (in the case of Bitcoin, using BIP327) is Bitcoin-style Schnorr signature (specified in BIP340). BIP340 signatures can only be used when spending Taproot outputs (specified in BIP341 and BIP342); it is not available inside P2SH. Since they're just signatures, no script is needed. Any place where one would want to use a signature to spend an output, MuSig2 multisig could be used instead of the normal (single party) BIP340 signing. The verifier is always just Bitcoin nodes that validate blocks and transactions, but again, they will not even be aware that MuSig2 is involved. To them, it's just a normal key, and a normal signature.

And regarding the initiation of the verification process—does a participant (e.g., one of the multisig signers) who has collected all the Rsum and ssum values create the transaction from the P2SH address? Or am I misunderstanding this flow?

One of the parties, or a coordinator, will aggregate the partial signatures and construct the full signature, which can then be placed in the spending transaction, which will make the spending transaction valid and broadcastable to the network.

What Happens Without Commitments? What could an adversary do if the commitments (ti) were not part of the protocol? What kind of attacks could occur, and how would they exploit the lack of commitments?

In MuSig1, without the first nonce-commitment phase, practical attacks are possible where an attacker starts multiple concurrent signing sessions with a victim, and succeeds in constructing a forged signature (for a message the attacker chooses, not agreed by the victims). In MuSig2, this phase does not exist anymore.

thanks you so much for you answer.......

"In MuSig1, without the first nonce-commitment phase, replay attacks are possible where participants can learn the private key of other participants. In MuSig2, this phase does not exist anymore".........

so commitments are not to prevent the rogue attack, but instead to prevent replay attack. can you tell me how these replay attacks can be performed to learn private key of other participants? or maybe giving me a reference from which I can learn more about? what's the link between a commitment and a private key

@allexj You may want to look at section 2.1 "The Challenge of Constructing Two-Round Schemes" in the MuSig2 paper for a brief description of the attack against MuSig1 without the nonce-commitment phase.

@nickler Thanks, I was confusing the replay attacks (which are possible when nonces are chosen predictably) with the concurrent signing attacks (which are possible without the nonce commitment in MuSig1). I have updated my answer.

@nickler thanks for the answer, I've read that paragraph of that paper. One question though: how should I imagine, in a real world scenario, the fact that the adversary opens up k different signing sessions? Why should a victim allow that? Also, I thought that multi signatures were performed by passing the partial signature data across the users "manually" until the required number of user is reached, and at that point, the last user can send the final signature to the bitcoin network.... so how can I imagine this "k different signing sessions"? Is there a protocol/system to support that?

@PieterWuille I also tag you

also, why X aggregate is the product? Shouldn't it be a sum? The same for R*, shouldn't it be a sum? Is there a technological/performance/security reason why it's a multiplication and not a sum?

@allexj A "session" in the MuSig2 sense is the time between the first and second round (i.e., the time while the victim needs to hold on to a private nonce whose public version has been shared with others). MuSig2 is secure even when a victim is participating in multiple such sessions at the same time. It doesn't matter how the partial nonces or signatures are shared; the concurrent attack just requires the attacker to have multiple at the same time, and being able to choose which ones to continue.

@allexj The product vs. sum is just a notation issue. Some people write the group operation (for elliptic curves, point addition) as an addition, and its repetition (point multiplication) as a multiplication. Others use a multiplicative notation for the group operation and exponentiation for its repetition. Note that the latter is where the term "discrete logarithm" comes from; in the additive notation setting it ought to be called "discrete division". The MuSig2 paper uses multiplicative notation.


text:
Running bitcoin-qt on a server
I need a full Bitcoin node running on a server. It's a Windows server - is there any advantage to running bitcoind over bitcoin-qt? I need the JSON API, to they need the server flag, I just figured that if something goes amiss it would be easier to take a quick look at the wallet if the GUI us running as opposed to the console.


text:
How to stream transactions on the network
How would I go about getting a stream of transactions broadcast on the Bitcoin network? Is this supported by the vanilla client?
I know that the client can notify me on new blocks and on all transactions that effect an address in my wallet, but I want to stream ALL transactions on the network.

What do you mean by "stream"?  What do you want to do with those transactions?  What do you want to be done for you?

@NateEldredge I want to do something similar to how blockchain.info displays transactions in real time. I just didn't know if the client exposed this anywhere, or not. I can see them in bitcoind's console - do I monitor console output?

Reading your question again, and looking at the comments, I think your question is slightly misinformed.
The standard bitcoin QT client is a node, which means that it receives the inventory of all transactions and relays all valid transactions it requests to receive (from the inventories). That's a bit of a mouthfull but read it carefully.
This has nothing to do with your wallet. It is a standard function of the full node on the peer to peer network.
What you appear to be mixing is the functionality of the wallet and the functionality of the node. These are two different things.
Bitcoin QT is unlike other (lightweight or SPV) clients which only request information specific to the addresses they hold, when trying to syncronise themselves with the network.
If you are looking to essentially print all transactions that are being relayed through your node, I think this would be pretty straitforward using something like Node.js or just running a continuous regular process which queries Bitcoind using RPC.

For https://getaddr.bitnodes.io/dashboard/#transactions-and-blocks-propagation, I keep open connections with all reachable nodes in the network and then capture all incoming inv messages with tcpdump and parse the pcap files for inv packets; inv type 1 for transaction and inv type 2 for block. In order to receive all inv messages, you need to ensure your relay bit is set to 1 in your outgoing version message. Be ready to handle 3 to 10 Mbps for the incoming invs and you should be able to get all transactions this way but they may not necessarily come from the origin node.

You don't need a full bitcoind node running. There's plenty of code to do that, I suggest you bitcoinj for Java and picocoin for C. It's a trivial task: connect to any peer (e.g. through DNS discovery) and parse the 'tx' messages it will send you.
I also published my own client library but it's for iOS and I guess you're looking for server-side stuff.
EDIT: if you don't want to get your feet wet at all a quick-and-dirty solution is the blockchain.info WebSocket API.

Theres a python script that connects to bitcoind and generates new tx and new block events here

Signing the transaction itself gets them to propagate on the network.  The miner fee is recognized by peers running btc nodes and by miners who are willing to accept the fee if their proof of work is accepted.
It sounds like you're trying to effectively replicate the real-time relaying of transactions?  Bitlisten.com has effectively done this and provides the audio output when this occurs in real-time.  They use Blockchain.info's api to recieve realtime transactions.

Yes, I know Blockchain.info can do it - I guess my question could be restated 'how do THEY do it?'

@Avram: The short answer is, they wrote a lot of custom code.

That's what I feared :) I will start by parsing bitcoind's output and see how far that gets me.


text:
Options for a Client Only C# application
If I want to create a client only, C# desktop application, what are my options for working with Bitcoin?

I could try to port BitcoinJ, which seems like a lot of overhead in terms of initial effort and keeping the project up to date.
I could try to create a local Bitcoin process which runs a tiny BitcoinJ-based server, and talk to it from C#.

Neither of these seem appealing.

I could use the Blockchain API.
I could set up my own server and run the wallets on the server.

Neither of these seem appealing either.
Anyone know of an easier way to run a Bitcoin client without a full blockchain using C#? I would ideally like users to retain control over their wallets, with the client code finding incoming payments and facilitating the sending of coins.

Why is it important that it be written in C#?

For LoB desktop apps, C#/WPF is the weapon of choice. You would need a reason to deviate from that. Java sucks for desktop apps, C++ is hopelessly unproductive for desktop apps. HTML5+JS might be an option, but that would be a bit limiting.

Well, having a bunch of existing code in another language would seem like a pretty good reason to me.  But what do I know?

Possibly, but it would be a little bit like the tail wagging the dog.

BitCoinSharp https://code.google.com/p/bitcoinsharp/

NBitcoin supports connection to the bitcoin network.
NBitcoin Github : https://github.com/NicolasDorier/NBitcoin
NBitcoin Nuget : https://www.nuget.org/packages/NBitcoin/
Intro : http://www.codeproject.com/Articles/768412/NBitcoin-The-most-complete-Bitcoin-port-Part-Crypt
Stealth Payment, and BIP38 : http://www.codeproject.com/Articles/775226/NBitcoin-Cryptography-Part
How to build transaction : http://www.codeproject.com/Articles/835098/NBitcoin-Build-Them-All
Using the NBitcoin Indexer : http://www.codeproject.com/Articles/819567/NBitcoin-Indexer-A-scalable-and-fault-tolerant-blo
How to Scan the blockchain : http://www.codeproject.com/Articles/784519/NBitcoin-How-to-scan-the-Blockchain (You can ignore the ScanState part)

Have you guys see this recent GitHub? I too have been poking around looking for a standalone library.
https://github.com/TangibleCryptography/BitSharper
I have it downloaded, just trying to fix dependencies so I can compile.
Looks promising.


text:
BlockNotify/WalletNotify - but without the console window
I use the walletnotify and blocknotify config options on bitcoind to have the server call two executables on new transactions/blocks. This all works fine. The two executables (Windows executables) are both designed to run without a console window, and they do.
That is, they do when I run them. When bitcoind runs them, I get a brief flash of a console window. As I run these on my development machine while developing, it's driving me to distraction. Does anyone have any idea to prevent this happening?

I took me some, but I think I have an answer. I went trough the source code and found the runCommand() function that actually starts the command provided by notify options (it is called mostly from main.cpp and the code runs in a separate thread).
From util.cpp
void runCommand(std::string strCommand)
{
    int nErr = ::system(strCommand.c_str());
    if (nErr)
        LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
}

It uses the standard C library method system(), which is probably giving you the flashing window. Normally one would use CreateProcess() (or similar) to prevent the flash effect and have much more control over the spawned process (I don't know why the developers chose system() here, but I guess it was just easier). I believe the behavior of the system() call is system dependent.
Also, when you say bitcoind, you mean the CLI interface of bitcoin, right? Is there a bitcoind console window running? As for a solution, you could edit the source code to use CreateProcess() with the DETACHED_PROCESS flag, that would do the trick.

I've not yet moved to using 0.9's new bitcoin-cli executable, so I just run bitcoind and talk to it over RPC. So yes, there is a bitcoind console window running. I don't really want to patch the code, so I guess I will just have to live with it. If it annoys me enough I will stick it in a VM :) Thanks for your reply.

I'm not quite sure what the conditions are for spawning a new shell, but I have seen this being different before on different machines. I for example don't get these flashes, no idea why. I could patch the code for you, but you'd have to recompile yourself (then we know for sure haha). You are welcome.


text:
When to check for confirmationsl
When monitoring incoming transactions for a web wallet, should I check for confirmations on a timer, e.g. every minute? Or should I check once every block by using blocknotify?

Every 30-60 seconds should be sufficient, but if you have access to a service that will notify you when blocks are found, that would be the fastest. A confirmation is just a block being found. Once the transaction is included in a block, that's its first confirmation (and it is no longer unconfirmed). Every block that stems from that block afterward is another confirmation.

Well this was kinda my thought. bitcoind uses the blocknotify config parameter to notify you on every block, so is there any need to check more than once per block?

No, a block is a confirmation. Therefore it's impossible for a confirmation to happen between blocks.

It depends how quickly you would like to notify the customer of their payment being accepted. When I make a deposit/payment, I would like to see it as soon as possible. I always get that uneasy feeling during the time between when I send coins and when I see it confirm in my account.
If I were you I would say every minute is acceptable (and easy to set up a cron for), I would notify when the payment has been seen (rawmempool), and when it has been confirmed the required amount of times to send or spend.

I guess what I want to ask is this - given that bitcoind can notify me when a new block is received, is there any point checking more than once per block?

If you would like to check for new unconfirmed transactions, yes, otherwise it would not be needed. I like seeing that my deposit was accepted asap, but truth be told this is not critical for payment processing. If you'd like to notify your customers that you have seen their payment sooner, then you can write a cron; if you just want to notify them their payment has been processed block notify should do the trick. Either way, the user will get used to how you process transactions. If you go with using block notify only you should expect clients to send you emails while they wait.

Thanks Mark. I use the walletnotify option to pick up transactions as soon as they are broadcast, and there doesn't seem to be any point in checking more than once per block. Think I have my way forward :)


text:
walletnotify and transaction malleability
To monitor inbound payments for a web wallet, I plan to use walletnotify to record the transaction IDs, then on each blocknotify I will check the number of confirmations for each pending transaction.
Obviously everyone is thinking about transaction malleability right now, so my question is this: in the event that the transaction ID is changed, or a block containing the transaction is orphaned etc - will I get another walletnotify with the changed TxId?

Yes. You receieve a walletnotify for every transaction your wallet sees that is relevant to it. Once when it is first seen, and once when it is seen in a block (first confirmation). These two may coincide, in which case you only get the confirmation one.
For mutated transactions, you will see a first one that never confirms (and in 0.9 will get a "-1" confirmations marker), and a second transaction that does confirm.


text:
Aborted escrow transaction
I know that multisig (n of i) transactions provide a decentralised escrow mechanism. Let's say we have a 2 of 3 address. What happens if funds are sent to the multi-sig address and say the seller is hit by a bus before posting the adorable Hello Kitty™ mug that you bought?
Does the 3rd party simply sign a transaction returning the coins to the buyer?
What about the general case of an address where n == i? Are the coins lost?

What happens if funds are sent to the multi-sig address and say the seller is hit by a bus before posting the adorable Hello Kitty™ mug that you bought?
Does the 3rd party simply sign a transaction returning the coins to the buyer?

Yes, if your address has a public key for 3 users, and you have problems receiving your goods, you can ask the arbitrator to sign review the situation and maybe create a transaction which pays you the money in the address. You sign, he signs, you get a refund. It's at the whim of the arbitrator.

What about the general case of an address where n == i? Are the coins lost?

Yes, if anyone loses their key, and the address requires same number of sigs as public keys, you cannot recover the funds.


text:
Bitcoin Core Multi-wallet limit to 333 wallets
Bitcoin Core 0.15.1 has Multi wallets support:
In the bitcoin.conf we can add multiple entries of:
wallet=wallet-1.dat
wallet=wallet-2.dat
wallet=wallet-3.dat
wallet=wallet-4.dat
...
wallet=wallet-350.dat

When Bitcoin Core starts, if the wallet file does not exists it will create it. which is great for our needs.
However, it always crashes on the 333 wallet. with db.log error:
Lock table is out of available locker entries

And debug.log:
2018-02-13 14:47:05 init message: Loading wallet...
2018-02-13 14:47:05 nFileVersion = 160000
2018-02-13 14:47:05 Keys: 21 plaintext, 0 encrypted, 21 w/ metadata, 21 total
2018-02-13 14:47:05  wallet                   36ms
2018-02-13 14:47:05 setKeyPool.size() = 20
2018-02-13 14:47:05 mapWallet.size() = 0
2018-02-13 14:47:05 mapAddressBook.size() = 0
2018-02-13 14:47:05 init message: Loading wallet...
2018-02-13 14:47:05

************************
EXCEPTION: St13runtime_error
CDB: Error 12, can't open database wallet-333.dat
D:\BitcoinCore\bitcoin-0.16.0\bin\bitcoin-qt.exe in Runaway exception

I also tried to minimize the -keypool=20 so that the wallets size will be much smaller in size, and the process of loading them is much faster.
I was suggested that this error is because each wallet.dat file is opened in the same BDB environment. The entire environment has a limited number of database locks, and it seems like 333 wallets hits that number of database locks.
The solution (which did not work) is to create a file named DB_CONFIG in the data dir, and put the following lines in that file:
set_lk_max_locks 400000
set_lk_max_objects 400000

By default it is 40000 and now 400000 (ten times more locks available)
But this gave the same results.
I tried also:
set_lg_dir database

With no luck.
I verified this on two different Windows 10 machines with 0.15.1 and 0.16.0. Same result. It always crashes when loading the 333 wallet.
Anyone have a solution to this?
I have put the list of wallets if anyone care to reproduce: https://pastebin.com/8wHD1tL3

For starters, you should file a bug report.  Even if there is a limit, the client should fail gracefully when the limit is reached, instead of crashing.  https://github.com/bitcoin/bitcoin/issues

Ok, I found a solution. Adding
set_lk_max_lockers 400000

Did the trick.
https://docs.oracle.com/cd/E17276_01/html/api_reference/C/set_lk_max_lockers_parameter.html
I tested and was able to auto-create and load 932 wallets, until I hit an out of memory error:
Logging region out of memory; you may need to increase its size
DB_TXN->abort: log undo failed for LSN: 227 171878: Not enough space
PANIC: Not enough space
PANIC: DB_RUNRECOVERY: Fatal error, run database recovery
PANIC: fatal region error detected; run recovery

Setting:
set_lg_regionmax 1048576

Resolves the above Logging region out of memory; you may need to increase its size issue.

can you please tell me where you kept this set_lk_max_lockers 400000 ?? in db.cpp ? https://github.com/bitcoin/bitcoin/blob/master/src/wallet/db.cpp#L166

I've created DB_CONFIG file in data directory of core daemon and given two values as mentioned but still its i am getting same issue daemon crashed after 250+ wallets can you please guide me or share how to use above things?

Yes DB_CONFIG  is in the datadir as far as I can recall. I think  I also minimized the -keypool=20 (or 10). In any case  I dumped this idea and I don't recommend going that path.

So is there any otherway..?

I mean if found anything ...please suggest .. thanks..

The other way is to manually manage the private keys/wallets. It's much harder but you are not limited in any way.


text:
Sending bitcoins to a "Sending address" in Bitcoin Core
I'm trying to understand some basic concepts in the Bitcoin Core (v.0.15.1) and in the bitcoin "world".
I'm using a testnet, and used https://testnet.coinfaucet.eu/en/ to send some bitcoins to a "Receiving address". it worked fine, and I can see the transaction/balance changed in Bitcoin core.
However if I send bitcoins from coinfaucet to a "Sending address" (Which is a public key as I understand) then I can't see any bitcoins in that address and the balance is not changed and no transaction is reported, although coinfaucet shows me a verified transaction.
What am I missing? Can't the sending address hold/receive bitcoins? what are the "Sending address" used for if I can't send bitcoins to it?
I assumed that when I want to send funds from my wallet to someone, I first move funds from the Receiving address to the Sending address and use that address. but I'm totally unsure of this assumption.
Any help will be appreciated.

EDIT: After dinging some more, I came to realize that the Sending address is just addresses you have sent or planing to send to. It has nothing to do with the Change address as described in the answer. That is why after I sent money from coinfaucet to a made up sending address I did not see any change in balance because that address is not mine. and after a re-scan I see it a watch-only.

That's interesting, I would also have thought it should work. I'll wait for the answers.

Just out of interest, what happens if you start Bitcoin Core also adding the -rescan parameter? - not sure how long it will take? In bitcoin-qt you might get a progress bar?

@Willtech, -rescan did not made any difference.

In Bitcoin Core, the sending address refers to the address that you have saved as a "contact" in the client. You can save the address with a nickname eg. Coinbase address.
The receiving address refers to the address which you can use to receive coins. The way Bitcoin works is that a transaction spends the unspent output from the receiving addresses. Hence, it depends on which receiving address you received coins from, your coin control and amount.
E.g.
1. If you receive 1BTC on 1AddressA and spend 1BTC in the client, the blockexplorer will identify the origin as 1AddressA.
2. If you receive 0.5BTC and 1 BTC on 1AddressA and 1AddressB respectively and you spend 0.5BTC, the blockexplorer will identify the sending address is 1AddressA.
3. If the scenario is the same as 2, and you spend 0.6BTC, the sending address will appear as from both and there will be another output going to another address in your client. It is called the change and the address isn't showed within the client. However, you can spend it in your next transaction, I don't know why there's no balance but what I know that the transaction to these addresses shouldn't appear as they are change addresses.
Why are they not on transactions list?
Because Bitcoin core using bip32
and change addresses transactions have different derive path.
Example
m / purpose' / coin_type' / account' / change / address_index
Normal addresses path:
m/44'/0'/1'/0/i

Change addresses path:
m/44'/0'/1'/1/i

That is interesting but, doesn't tell the asker what happens if I send some BTC to a sending address from my wallet, instead of a receiving address.

You will not be able to see any transaction, just the amount you received in your wallet balance.

@Adam thanks. problem is that I don't see any amount change in the wallet balance. Also getbalance RPC won't show any changes

can you try bitcoin-cli importaddress "address" true This may take a long time since it will rescan the blockchain.

@Adam, Yep. that made Bitcoin core show these transactions as watch-only (what is that?...). Can you please explain what exactly happen with bitcoin-cli importaddress "address" true? will theses transactions never show unless you do the above?

Whether you've sent to an address that doesn't belong to you or for some reason the address was not added to your wallet. Please try to send what you have to another address, and you will figure out what happened.

@Adam, can I send it to my own wallet address? if I do, I get "Payment to yourself". I'm completely lost sorry. so the “Sending address” is the change address? Do I even need to create "Sending address” in my wallet? sorry for nagging.

You can send to any address you want, no worries at all. Yeah, its change address. Bitcoin core will create these addresses automatically when you're sending some payment. for instance, if you have 1 BTC and you're sending 0.4 BTC so 0.6 minus fee will become in change address.

Another thing that happened after the importaddress was that the "Sending address" moved to the "Receiving address" tab. and now I have no "Sending address" at all. go figure... sigh

Yeah because it's added to receiving addresses after you imported it.

After digging some more, I don't think that the "Sending address" is a Change address at all. they are just the addressees you sent/d money to. can you prove me wrong?

Please read the first line of the answer.

@Adam, I did read it. but your answer also says that the sending address is the Change address. or did I misread it? I also asked you "so the “Sending address” is the change address?" - you answered "Yeah, its change address". How is that related to the "Sending Addresses"? Don't get me wrong, I'm grateful for you answer, but just can't see how Change is related!

In Bitcoin Core, the sending address refers to the address that you have saved as a "contact" in the client. So when you send to someone's address it will be in sending addresses. and like so the system does. when you have a change it the system will send it to change address and it will be in that category, don't confuse your self with that GUI stuff.