text:
Given a Bitcoin transaction as JSON data, how can I determine the number of confirmations?
According to blockchain.info, 4,198 confirmations have been received on the following Bitcoin transaction at the time of this writing. Give then following Bitcoin transaction as JSON (ref: transaction on blockhain.info as JSON) how can I determine the number of confirmations?

Transaction as JSON
{
   "ver":1,
   "inputs":[
      {
         "sequence":4294967295,
         "witness":"",
         "prev_out":{
            "spent":true,
            "spending_outpoints":[
               {
                  "tx_index":0,
                  "n":0
               }
            ],
            "tx_index":0,
            "type":0,
            "addr":"1BiYTVfoAWpEf5vTCVyWgWzsbdTbi3X4Lb",
            "value":4371338,
            "n":1,
            "script":"76a914758c92328cb8f0d5a9e2bc6a1b27b6fdf83fa86588ac"
         },
         "script":"483045022100f6d8e0e386079721dc286d25c88c5cddd8733ee3d93247f3ff0127e8aa7dcb9a02206ce2b7e524e4796e93688442dcc95bb7c8e2bcf3a46ac660633fac3e0becfd5e012102a9dba5ef4653f48190bf6b12130f001fe14cda8b8e2e06bf2e96b9cf3c442503"
      }
   ],
   "weight":760,
   "block_height":615893,
   "relayed_by":"0.0.0.0",
   "out":[
      {
         "spent":true,
         "spending_outpoints":[
            {
               "tx_index":0,
               "n":0
            }
         ],
         "tx_index":0,
         "type":0,
         "addr":"3BMEXDcDGPjGGR6MHiFiHRPfz6LeGeYYM3",
         "value":4366812,
         "n":0,
         "script":"a91469f3746a2b4246695de6ae4fd0d2c27221b1cd9d87"
      }
   ],
   "lock_time":0,
   "size":190,
   "block_index":0,
   "time":1580790109,
   "tx_index":0,
   "vin_sz":1,
   "hash":"406fe52a8cb99cfdc3ed6cc3e2ef461608e369943a9c1f4132421d3de425e66c",
   "vout_sz":1
}

Confirmations are nothing but just the number of blocks added after the block the transaction was added in. So accordingly, during the time of writing, the current block is 620093 and your transaction was added in block 615893
So if you subtract these two , current block - tx added block(620093 - 615893 = 4200), you will get the total number of confiramtions, which is near to your block confirmations (4198)
Hope this was helpful. Have a great day!

Thanks, great info!  Any idea how I can get the current block height?

I should have looked at the same site I reference earlier.  After a quick search I found this URL, which returns the block height among other things as JSON.  https://blockchain.info/latestblock

Yes, that's a great way to get the block height. Now you just to extract both of them and subtract them to get total confirmations


text:
How does clearing & settlement work on crypto exchanges
I understand that this may differ between trading venues, and may perhaps depend on what specifically is being traded, but I would like to understand, in practice, how the post-trade process works in exchange-traded crypto.
For example, on an equities exchange (e.g. SETS), a participant (often a broker) will have an order matched against another participant's order, and the exchange will capture this legally-binding agreement to transact. A central-counterparty clearing firm (e.g. LCH) will novate the positions of both participants (as well as other participants) and net off the multilateral positions at EOD. This removes the risk of counterparty default during the period of time between trade and settlement. However it involves multiple firms performing a chain of operations which can take days to complete.
Crypto-currencies are distinguished by having a distributed ledger - so an OTC transaction can settle 'automatically' without requiring this process (assuming crypto-for-crypto trade). However I think this would be extremely onerous for the blockchain, and so the exchange presumably has some form of netting layer, between the matching engine and the actual on-chain transaction. I can see a few different ways for how this might work but haven't been able to find out how it actually does work.
Can you explain the post-trade process on e.g. Kraken / Coinbase / Binance, and how these firms ensure that two matched orders will settle on-chain?

Do on-chain transactions actually happen when matched on-exchange? Or just  e.g. when a user cashes out their exchange account into a local wallet

Does the process differ if one is exchanging one cryptocurrency for another, versus fiat for crypto?

How do they ensure privacy if transactions are trackable in the blockchain? (As a systematic trader, it would be quite bad if other participants knew your positions and which trades you had recently made!)

Do on-chain transactions actually happen when matched on-exchange? Or just e.g. when a user cashes out their exchange account into a local wallet

Just when users deposit or withdraw from their account with the exchange. There is no on-chain activity from just trading; it's just incrementing one account's internal value on the exchange and decrementing another (and for the asset traded against, in the other direction).

Does the process differ if one is exchanging one cryptocurrency for another, versus fiat for crypto?

No.

How do they ensure privacy if transactions are trackable in the blockchain? (As a systematic trader, it would be quite bad if other participants knew your positions and which trades you had recently made!)

Positions are not visible on-chain.

Thank you Pieter! So you are saying that exchanges basically have their own wallets, and when a participant opens an account, a virtual account is created for him. The participant then transfers fiat or crypto to the exchange, Trading is then all done 'virtually' until he wants to withdraw cash or crypto; at this point, the cash or crypto is transferred from the exchange to the user. So all of the clearing and settlement is effectively handled by the exchange itself. Do exchanges manage these deposits using a fractional reserve system? Is there no true peer-to-peer on-chain trading exchange?

Generally yes, exchanges create 'virtual' accounts for each user because this prevents them from overpaying on fees. Owning the accounts allows the exchange to consolidate UTXOs, which helps with fees down the line too as well as lowering full node storage requirements. The exchange will still control the funds at the end of the day its unlikely they will opt to give the users more control. This is why they are called 'centralized' exchanges. For a more decentralized option look at bisq: https://bisq.wiki/Frequently_asked_questions#How_is_Bisq_different_from_other_decentralized_exchanges.3F

source: Stack Exchange

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

sort: votes


text:
RPC security of bitcoind node
If I have a fairly default bitcoin.conf file, let's say:
rpcport=8332
txconfirmtarget=6

ie: notably one where I don't specify things like rpcuser, rpcpassword - is this insecure?
As I understand, this lets the node be queried locally without an authentication. However I'm not sure this is any more dangerous than wallet.dat sitting around - local access would mean private key access.
Are default settings of bitcoin insecure?

ie: notably one where I don't specify things like rpcuser, rpcpassword - is this insecure?

No, Bitcoin Core by default creates a RPC cookie file in the data directory on startup which is used in place of static authentication. Specifying a rpcuser and rpcpassword is deprecated, and they can't be blank regardless.

Gotcha. What's the name of that file by default? Not seeing it on disk nor in the documentation.

The name of the file is ".cookie", in the usual Bitcoin Core data directory.

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


text:
Running both bitcoind and bitcoin-qt for use with lightning
I've been toying around with bitcoin & lightning nodes.
I like having the Bitcoin Core Qt GUI around for things, but also like being able to change specific configuration / startup flags (maybe eventually contributing) with the source + bitcoind.
My proposed solution is to download Qt GUI (current version 0.20.1) and then get the same version from github and share the same bitcoin chain database.
To do this, I want to have the same version. Is this as easy as:
# I downloaded 0.20.1 .dmg file from Bitcoin Core and installed it, thus I need that tag from Github
git clone https://github.com/bitcoin/bitcoin.git
git checkout tags/0.20.1
# ... do build here

Then, depending on what I'm doing I run either 1) Qt, or 2) bitcoind, but never at same time.
Any additional steps I need to do to check the versions are the same? Is there an easier way to achieve this? Maybe it's just safer to build Qt stuff myself...

There's no particular issues with running both the daemon and the QT using the same data directory, you're also protected against running them both at once due to locking. Most versions, especially within a single major release, are compatible so there's no burning concern about keeping them exactly in sync with one another.

OK, wonderful! So the steps I've outlined above seem fine to achieve that?


text:
Running ERC20 contract on RSK
Disclaimer: originally asked on the ETH SE site, but advised to post here.
I have been reading about RSK lately and was wondering about the compatibility and possibilities, so I wanted to ask for some basic info in case there's someone more knowledgeable.
I have a smart contract running on the Ethereum network (and more to come). The contract is based on the ERC20 standard. So, this smart contract, with its setup today, would it be possible to make it use the RSK network instead of Ethereum?
If yes, what could be the pros/cons (eg. cheaper/faster transactions) and whether it would make sense to do the transition?
If not for the current contract, then maybe for future ones?


text:
Bitcoin account balance computation power
As far i know, In bitcoin there is no where storing the account balance in db straight forward. If the person wants to know his account balance from his client app the server will calculate all his transaction of credit and debit return the sum value.
If this above is true when person A has previous transactions like 20,000 and Person A wants to transfer some money he has to Person B.
When this process starts the bitcoin mining server has to calculate all his transaction from beginning to check whether the person A has enough balance or not and this has to be done in other mining server also to verify.
In this case as long as the person has 1 lac transaction, to calculate the balance the computation process will be heavy right ? more computation process uses more cpu cycles and power which affect the maintain cost of the computer and transaction fee may go high.
Please explain how its happening ?

Possible duplicate of https://bitcoin.stackexchange.com/questions/62011/blockchain-and-transaction-validation

https://medium.com/@ConsenSys/thoughts-on-utxo-by-vitalik-buterin-2bb782c67e53
From this i can understand well it uses UTXO but what if the UTXO has million transaction with value of 0.000001 BTC. At the time that the person wants to send 1.1 BTC  the system has loop through 1 million records to match 1.1 BTC and finally its going to return false because the  user has balance is 1 BTC. looping 1 million record seems heavy computation for me and the computation process also used some money (electricity)...

that is not how the UTXO set works. Bitcoin does not use balances, it uses UTXOs. UTXOs are explicitly referenced when they are spent, so it is trivial to just look up each individual UTXO. A UTXO represents exactly one thing, not "million transaction" or multiple transactions.

no UTXO is a collection of unspent or received transaction right ?
There can be chances of having N number (millions) of transaction in UTXO set..
am i right ?
https://bitcoin.stackexchange.com/questions/4301/what-is-an-unspent-output/4304#4304

No, a single UTXO is a single item: a transaction output. It is not a collection of transactions or outputs. The UTXO set is the collection of UTXOs. There are millions of UTXOs in the UTXO set, but it does not require significant computation to retrieve them (retrieval is O(1)). Calculating the sum of the inputs is only O(n) and is not very computationally expensive. The computationally expensive parts are in signature validation and other checks that need to be done, not balance calculation.

Understand bit.. when the transaction happen the amount will be taken from UTXO set. the process will use UTXOs is LIFO or FIFO ?

Neither. UTXOs are specified and the sender can choose UTXOs in whatever order they want.

Let us continue this discussion in chat.

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


text:
Fundamental Question on Bitcoin: How would one convert his "bananas" into bitcoins?
In one of the presentations by Andreas Antonopoulos on Bitcoin, he said that "there are 6 billion people in this world who have no banking facilities, who live in places where they have cash or barter based societies. In these places, where banking services will never reach and the nearest bank is 100 miles upstream, where the only form of technology is a Nokia 1000 feature phone, every phone become a banking service"
My question is this. In a scenario as described above, how would one transact his/her hard money or the farm products (say bananas) using a basic phone without any banking facility? In other words, how will one convert his "bananas" to bitcoins?

What actually banking service provides to you in your context?

how would one transact his/her hard money or the farm
  products (say bananas)

It is not possible to transact/transfer/convert bananas to anything else. The same situation is with any other things in real and online world.
So, if you have bananas you have only one possibility: exchange them for something to a neighbour. Give me your bananas and I will give you my old shoes. If we are far away to each other, we should construct a chain of exchanges: you sell your bananas to somebody (exchange for your local money), he delivers bananas and sell them to me (exchange for my local money).

using a basic phone without any banking facility?

We do not need phone and banking at all here. But if you want to use a phone in this chain of exchanges, you may have it in your pocket.

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


text:
Mixed inputs / outputs in liquid transaction
Can one given liquid transaction be made of a mix of blinded and unblinded inputs and/or outputs?
If for example I have 1 input blinded + 1 input unblinded and then 1 output unblinded, one would be able to find out the value of the blinded input. That would generate privacy risks, right?


text:
Why the difference in sats on Collaborative Connector Closures?
According to https://www.arkpill.me/deep-dive, the value added to X is 240 sats when dealing with 1, 10 or 100 sats coins, but 280 sats when dealing with >100 sats coins.
Why?

The difference seems to have gone to the relay fee, but I don't understand myself why there would have to be a difference in relay fee, the txs seem identical in size.

Exactly. And to be honest, I don't know if 450 - 280 = 170 or if 450 - 170 = 280, the documentation is not clear.

Hi @StevenRoose, your comment looks like an answer to me (even though it’s short). Please don’t answer the question in comments, but make an answer post instead when you are answering the question. :)

As explained in my comment, the difference in output value is because of a different relay fee for these transactions.
I don't however understand why these transactions would have a different relay fee value. It might be an oversight.


text:
What can we do with XRP?
I'm trying to get my head around XRP, "the native currency of the Ripple network".
I understand that it's a currency that's only used within the Ripple platform to allow for transactions and serve as a "currency of last resort".
So I would imagine banks and financial institutions are quite interested in buying XRP so they can join the platform, since it allows them to cut off their operational costs.
However, it seems there is another group of people interested in XRP purely for speculative purpose.
What I don't quite understand here is how those people will actually "use" XRPs since it can only be used within the Ripple platform. Of course they will hold it until it surges in value but that would mean that, during that period, the XRP held by those speculators will not be available within the Ripple platform unless they "use" them in someway within the platform.
However, since those individual speculators aren't banks or financial institutions that are doing transactions with different currencies, I don't see any use cases of XRPs for them other than selling them, which would mean they are basically "hoarding" XRPs while waiting for their values to go up.
So I guess my questions are:

What does it mean to buy XRP as an individual OTHER THAN speculation?
(If investing in XRP could mean something other than speculation) How can we "use" XRP to do something other than speculation as an individual?
How is it possible that the Ripple protocol can operate even when there are many people buying XRP and therefore "holding" it, making it "unavailable" to the rest of the network. (I would imagine there are constant supply of XRP, which is enough to keep up with the "hoarded" XRP)

Any suggestions will be really appreciated.
Thank you.

What does it mean to buy XRP as an individual OTHER THAN speculation?

You can also use it as a means of payment and as a means of exchange for other assets on the network.

(If investing in XRP could mean something other than speculation) How can we "use" XRP to do something other than speculation as an individual?

You can pay it to other people to settle obligations. You can exchange it for other assets on the XRP Ledger. You can use it to fund transactions on the XRP Ledger to issue, redeem, transfer, or hold other assets.

How is it possible that the Ripple protocol can operate even when there are many people buying XRP and therefore "holding" it, making it "unavailable" to the rest of the network. (I would imagine there are constant supply of XRP, which is enough to keep up with the "hoarded" XRP)

XRP that is held is effectively out of circulation. Taking XRP out of circulation increases the value of the XRP remaining in circulation by reducing the effective supply. This makes it possible to use the remaining XRP for higher-valued transactions because its value is higher.
But even more importantly, speculation creates demand and trade volume. Because there are speculators who buy and sell XRP for US dollars, there is a robust trade between XRP and US dollars. This helps to establish and stability XRP's value and to assure that there are easy ways into and out of XRP for people who use XRP as a vehicle currency.
On one day recently, speculators traded about $1 billion worth of XRP. This helps to provide a reliable and stable measure of XRP's value without which it could not be used as an intermediary asset.

Thank you for your detailed answer. It's become much more clear now.
Just to make sure I understood correctly, I'd like to ask you a few more questions, which I'll post as another question on this forum. I'd appreciate it if you could answer it as well.

authors: Павел Цаплин


text:
Bitcoin Cash: Reasons for price fluctuation
I'm trying to understand the possible factors that affect the price of Bitcoin Cash (BCH).
In my understanding, one of the reasons why its price fluctuates is the presence of miners who are attracted to the chain where the difficulty level is relatively low, which in turn will also attract a lot of people since the chain now looks more reliable than the other chain (i.e. that of Bitcoin) with more miners maintaining the network.
Of course, there can be other factors, such as people who've acquired bitcoins, obtained the same amount of BCH, and then immediately sold them to earn a "quick buck", causing its price to go down.
My questions are:

Is the above argument valid?
If so, could there be some other elements that can affect the price of BCH?
If not, what do you think are the reasons behind the price fluctuation of BCH?

Any ideas or feedback will be greatly appreciated.
Thank you.

There is really no way to know why the price of BCH went up recently, but a few of the possible reasons are:

People converted BTC to BCH after the planned 2x hard fork fell through source
People are taking advantage of the HF call-off with a little pump and dump action source 1 source 2


text:
What is the difference between a cryptocurrency, a digital currency, and a virtual currency?
I'm wondering what are the differences between the three terms.
I have the impression that they are used somewhat interchangeably, with people talking about Bitcoin being the most popular "virtual currency" etc.
Some people say virtual currency is the subset of digital currency, while others argue conversely.
Any suggestions will be appreciated.
Thank you.


text:
P2SH address as a product of public keys
Assuming the multisig 2 of 3, if I do have extended public keys (xpub) for all 3 cosigners (with proper derivations), can I somewhat get the result address (P2SH)? How to calculate the "script" out of these public keys?
Would be cool to have scheme for doing so or a code/pseudocode in python if possible.

Let's start from multisig 2-of-3 redeem_script template:
OP_2 OP_DATA_33 key1.public_key OP_DATA_33 key2.public_key OP_DATA_33 key3.public_key OP_3 OP_CHECKMULTISIG
which ties the keys together.
All you need to do here is generate some 3 keys (33 bytes each) from those xpubs (BIP-0032) and concatenate the keys with opcode bytes.
Raw bytes of this script would be (note: the + operator below indicates byte concatenation):
0x52 + 0x21 + key1.public_key + 0x21 + key2.public_key + 0x21 + key3.public_key + 0x53 + 0xae
From that, you compute:
redeem_script_hash = ripemd160(sha256(redeem_script))
Then, you can construct the raw output locking_script:
OP_HASH160 OP_DATA_20 redeem_script_hash OP_EQUAL
by again concatenating the raw bytes:
0xa9 + 0x14 + redeem_script_hash + 0x87
That's it!
You can either use the raw bytes directly if you're constructing a raw transaction yourself, or encode it into a Bitcoin address so other wallets can pay into it.
When time comes to spend, the input script will be of the form:
OP_0 OP_DATA_71 key1.signature OP_DATA_71 key2.signature OP_PUSHDATA1 105 redeem_script
and its raw bytes will be:
0x00 + 0x47 + key1.signature + 0x47 + key2.signature + 0x4c + 0x69 + redeem_script
Here's is a great reference for P2SH & multisig: https://btcinformation.org/en/developer-guide#multisig


text:
Ypub test vectors missing for mainnet
Following extended key derivation scheme in BIP49 is there a publicly available test vector repository for mainnet? The test vectors in https://github.com/bitcoin/bips/blob/master/bip-0049.mediawiki#test-vectors are for testnet only.


text:
When commit_fee (fee_per_kw) renegotiation?
Looking at my channels on lnd node, fee_per_kw values are different for some channels (13332 or 6422).

How is the fee_per_kw calculated when opening the channel? Does it take current bitcoin fees estimation at some threshold?
When should it recalculate (is it automatic?)
Is there a manual way of setting the custom fee_per_kw parameter?
Is there a manual way of triggering recalculation?

(I'd love some read materials on this topic as well if available).


text:
Script type test vectors
I'm looking for test vectors, assuming xpub or public key to derive various script type addresses out of it. Something along the line of https://bip32jp.github.io/english/  but not only for P2PKH, but all P2W and P2T types as well (ideally with P2SH types too). Is there a place to find them, or could someone post few of these vectors in the answer?


text:
Java bip32 library
I'm looking for java library that will cover bip32 address derivation (xpub to P2PKH, P2SH, P2WSH, P2WPKH, P2SH-P2WPKH). There seem to be a lot of libraries covering P2PKH, but not much else (like bitcoinj). Could anyone help me in this regard?


text:
testnet faucet "Bots are not allowed here"
Why does this testnet faucet
Testnet faucet
always say "Bots are not allowed here" on both
my Android Chrome browser
AND
my iPhone Chrome browser
???


text:
Block validation process
Can some one explain how the block validation is done in blockchain based system with suitable example.

Possible duplicate of Block Validation: who does it? How much it costs? And is it present in all protocols?  ... See similar questions

There are a lot of steps to validation, you can follow the process at the following code in a Bitcoin Core node: https://github.com/bitcoin/bitcoin/blob/ed9a2a37c1878ba6b75c39b7cb263dc16c52a295/src/validation.cpp#L3027


text:
How do fees get processed in bitcoin? (protocol question)
If the fee isn’t written into the ledger, and it’s just the difference between the input transaction amount and the output transaction amount, how does the miner prove he has access in his wallet to the fee amount?

how does the miner prove he has access in his wallet to the fee amount?

Miners do not prove this.
The ability to reap the difference in inputs and outputs in a coinbase transaction is baked into the bitcoin consensus rules.
Any miner who was lucky enough to find a block can sum all the differences in included transaction inputs and outputs in a block and aggregate them in the coinbase transaction.
The miner can then spend the coinbase outputs 100 blocks later.
Edit #1: @eponymous's comments regarding potential reduction in bitcoin supplies if miner does not reap all transaction fees.
Suppose a miner elects to not reap all the difference in inputs and outputs in a coinbase transaction, then the supposedly total supply of bitcoins will be reduced. The 21M bitcoin supply is a theoretical limit that assumes that all miners reap all potential transaction fees and block subsidy rewards.
Example: Total difference in inputs and outputs is 1 BTC, but miner reaps 0.9BTC. Then 0.1BTC will be lost from circulation.
Edit #2: Included @pwuille's excellent explanation on the existence of 21M bitcoins

Note that they don't necessarily have to take the fees they're entitled to, but some value less. It's an upper threshold not a requirement.

@eponymous: if they took less, would that bitcoin be lost forever?

Yes. It’d be gone forever.

Yes, the supply is less than 21M due to some coins never having being mined.

See https://bitcoin.stackexchange.com/questions/38994/will-there-be-21-million-bitcoins-eventually for details.

We have the rule for transactions that
txFee = Σ(inputs) − Σ(outputs)

However, the coinbase transaction is exempt from the above rule, but restrained by a rule on the whole block:
Σ(inputs) > Σ(outputs) − blockSubsidy

This latter rule allows the miner to send themselves all transaction fees and the block subsidy in a coinbase output. Coinbase outputs are only allowed to be spent after they have matured to 100 confirmations, but otherwise work just like any other transaction output. Thus, the miner can prove that the funds are his just like any other user.
The block subsidy follows the reward schedule: How many bitcoins will there eventually be?


text:
LIGHTNING LND failed to load config: lnd.conf: unknown option: logdir?
In my lnd.conf:
logdir=Z:\LND\logs

logdir is a valid option according to:
sample-lnd.conf
but I get:
Z:\LND> .\lnd --configfile=Z:\LND\lnd.conf
failed to load config: Z:\LND\lnd.conf:55: unknown option: logdir

I am running LND lnd-windows-amd64-v0.14.2-beta on Windows 10.
I get this error w/ other valid .conf options too.
When I comment out the offending option, LND launches as expected:
Z:\LND> .\lnd --configfile=Z:\LND\lnd.conf
2022-03-16 09:28:54.763 [INF] LTND: Version: 0.14.2-beta commit=v0.14.2-beta, build=production, logging=default, debuglevel=info
2022-03-16 09:28:54.763 [INF] LTND: Active chain: Bitcoin (network=testnet)
2022-03-16 09:28:54.763 [INF] RPCS: RPC server listening on 127.0.0.1:10009
2022-03-16 09:28:54.763 [INF] RPCS: gRPC proxy started at 127.0.0.1:8080
2022-03-16 09:28:54.763 [INF] LTND: Opening the main database, this might take a few minutes...
2022-03-16 09:28:54.773 [INF] LTND: Opening bbolt database, sync_freelist=false, auto_compact=false
2022-03-16 09:28:54.773 [INF] LTND: Creating local graph and channel state DB instances
2022-03-16 09:28:54.783 [INF] CHDB: Checking for schema update: latest_version=24, db_version=24
2022-03-16 09:28:54.783 [INF] LTND: Database(s) now open (time_to_open=10.384ms)!
2022-03-16 09:28:54.783 [INF] LTND: We're not running within systemd
2022-03-16 09:28:54.783 [INF] LTND: Waiting for wallet encryption password. Use `lncli create` to create a wallet, `lncli unlock` to unlock an existing wallet, or `lncli changepassword` to change the password of an existing wallet and unlock it.

The .conf file needs the section annotations.
As soon as I added:
[Application Options]
logdir=Z:\LND\logs

just above the logdir option everything works accordingly & the logdir is created as expected.


text:
Bitcoin learning games?
I'm seeking ideas for very simple games involving sending/receiving Testnet Bitcoin?
I'm gathering some noobs to show them how to send/receive bitcoin.
Once we issue a coupla transactions, I was thinking it might be fun to turn it into a game to increase the learning.
We're using Blockstream Green wallet to do this because it has an easy option for Testnet (thank you to r/Bitcoin for teaching me this).
I'm prepared to send Testnet Bitcoin by virtue of these faucets:
https://en.bitcoin.it/wiki/Testnet#Faucets

Padawan Wallet seems very fitting to your usecase, from the website:

Padawan is application is a place to learn the common features of mobile bitcoin wallets.
It uses bitcoin’s testnet, an alternative bitcoin network used
globally and built exclusively for testing. The coins on this network
do not have any value, but they otherwise look and behave just like
normal bitcoins!
This wallet is built for users of all ages to experiment and learn
about bitcoin in a risk-free environment.

https://padawanwallet.com/
Regarding games, you could try to play board games for testnet coins, Poker for example.

Padawan looks interesting but it's not available for iOS phones, just Android.


text:
"Wrong Volume" ? Need testnet3 tBTC?
Why do I keep getting "Wrong Volume" from all the testnet faucets?
What does that mean & how can I fix it?

I'm a developer trying to write an educational & safe testnet/signet/regtest wallet.
I need tBTC for testing & transacting between myself & others.
If there are any kind souls w/ any testnet3 tBTC to spare, here is my address:
     tb1qv5s0m4q2vkj9tl3zfj60szzw0qdstjuu6eznj7

1 to 5 tBTC would be helpful (or, indeed, any amount).
Thanks in advance...?

Which testnet faucets have you tried, and which is the one in the screenshot?

screenshot: https://bitcoinfaucet.uo1.net/send.php

https://en.bitcoin.it/wiki/Testnet#Faucets

You said that you were trying to use the faucet on bitcoinfaucet.uo1.net. The site shows its limit for payouts near the top:

I would expect that if you set an amount larger than that, it will might return the "Wrong volume" error. Unfortunately, some people have started monetizing testnet coins and are trying to monopolize coins by sucking up everything from easily accessible sources. The only solution that comes to mind is to frequently restart testnet in order for them to lose money, but that also makes it less useful to other users.
You could try the other faucets listed in this community wiki, or try to find an individual that can send you some.

I'll check out those other sites thanks.
I do not exceed allowable amounts from the sites.

just reviewed that list.  The only ones that "work" are those I've tried already.  The others are listed as defunct sadly.


text:
Regarding block validation in blockchain
In mining process, miners validate the block based on proof of  work or using some other consensus mechanism.
Miners also validate the block. So in this validation process, miners validate only hash value of current block (or) they validate the entire transactions and then they validate the hash value of current block.
Please clarify this.

But how they check each transaction from block header.

Full nodes validate everything. A miner must be running a full node. Not all full nodes are miners, but all miners are full nodes.
A full node validates everything in a block; it validates the transactions, it checks the block header is correct, and checks the Proof of Work is correct. So in the validation process, full nodes (and thus miners) will verify that the PoW is valid (hash of the block header is less than the target), that the block header is correct (contains the correct target, merkle root, etc.). Then they will check that each individual transaction spends UTXOs that exist, check that the scripts validate to true, and check that the output amounts are valid (less than or equal to the input amounts). They will also check that the coinbase transaction pays out the computed maximum payout for the block (subsidy + transaction fees).

But how they check each transaction from block  header

Blocks are more than just the header, they contain transactions. The transactions are sent along with the block header to form an entire block.

So if i am saying that node A is having some block (B) and other nodes X,Y,Z are wants to validate the block B than  node A has to send the block B to nodes X,Y,Z. This block B contains the hash of previous block, time stamp, nonce and Merkele root where Merkle root are created from list of transactions. So   Node A send the entire things included the list of transactions to other nodes X,Y,Z  or node A send only block excluding the list of transactions for the validation process

In general node A will send the entire block B with all of its transactions to nodes X, Y, and Z.

So if node A send the transactions with block header to other nodes X,Y,Z than it always possible that some one on the way, tempered the transactions  so how other nodes validate the transaction.

If a transaction is tampered with, nodes X, Y, and Z will determine the transaction is invalid. They validate it in the same way, just conclude with a different result.


text:
Block validation in blockchain
if i am saying that node A is having some block (B) and other nodes X,Y,Z are wants to validate the block B than node A has to send the block B to nodes X,Y,Z. This block B contains the hash of previous block, time stamp, nonce and Merkele root where Merkle root are created from list of transactions. So Node A send the entire things included the list of transactions to other nodes X,Y,Z or node A send only block excluding the list of transactions for the validation process.

Yes, in general node A will send the entire block with all transactions in entirety to other nodes for them to validate. The receiving nodes will receive an entire block with everything in the block header and every transaction in the order that is required by the merkle root and they will validate everything in that block.

There is a network optimization where node A would send the block header, the coinbase transaction, and the list of transaction ids of the transactions in the block. This saves network bandwidth. By using a list of transaction ids (and not the transactions entirely), node A assumes that the other nodes already have those transactions because they were in its mempool (i.e. those transactions were unconfirmed and broadcast to the network prior to a miner including them in a block). The receiving nodes would then pull those transactions out of its mempool and reconstruct the block. If they are missing any transactions, those are requested from node A.
The end result is that they have constructed a block that looks exactly the same as the one that node A has, i.e. it is the same block. They can then pass this reconstructed block through the exact same verification functions as they would have with any other block received in entirety.
This optimization is known as Compact Blocks.

Either way, when node A sends a block to another node, that node will end up with a block that has the block header and all of the transactions contained within the block. Node A always sends the list of transactions included in that block.


text:
Can I cash out Bitcoin without proof of provenance?
I have around 25 BTC from back when Bitcoin was around 10$ or lower. At the time, a friend sent them to me and I never thought they would ever be worth much. Since that time, I've moved them around and don't think I still have any original wallet from around that time. I don't have any solid proof of the original transaction (maybe some old Skype chat log). I'm worried that if I tried to cash them out and withdraw to my bank account, I will lose all or worse.
From what I understand, if the government decides to investigate the transaction, they could seize it and put me in jail? The burden of proof is on me right? What's the best/worse case scenario? Any suggestion on how to approach this?
A general answer would be nice but to be specific, I'd be cashing out to either my USA or Canadian bank account.

I'm voting to close this question as off-topic because stack exchange is not the appropriate place to ask for legal/accounting advice.

Generally, if you’re in the USA/Canada, then the govt is not going to throw you in jail for cashing out your bitcoin that was received legitimately. They will expect you pay taxes accordingly, but you’ll need to talk to an accounting professional for more info about that.

In the US, nobody is likely to care if you assume a zero basis and pay capital gains tax on the full value of the bitcoins. If anyone asks, just explain that you acquired them back when they were nearly worthless. There are a lot of people in that same situation.


text:
Migrate lightning node daemon software
Is there a way to migrate from c-lightning to LND without having to close and reopen all channels?

As the lightning network is a specified protocol and as both implementations are open source and spec compliant it should theoretically be possible to migrate from one implementation to another.
However practically spoken you will need a software tool that transforms all the internal data formats of lnd to the ones used in c-lightning without messing the nodes state. I am not aware of any tool that converts the internal data formats. That being said either you go out and create such a tool or you will have to install a new node (even with a new nodeid)

Connor said on a github issue sometime back that c-lightning and LND uses a different seed formats and key derivation techniques which should impede the migration. I was unsure if these could be overcome by transforming internal data formats.

I just realized that the fact that lnd supports multiple channels between two peers which c-lightning from a software architectural design do and will not support. this migration also in practise will not work in every situation / in general.


text:
Obtaining 12 word mnemonic from Private & Public Keys
After a recent upgrade to Jaxx wallet my Litecoins and my transaction history are lost.
The 12 word mnemonic opens up a wallet with zero Litecoin balance even though the public key address from the earlier Jaxx wallet shows the coins are available and unspent on blockchain.My mnemonic seed has not changed yet Jaxx wallet is not the same.So apparently there may have been a bug in the seed derivation path or ......
Jaxx support is not able to help and they say I am not using the correct mnemonic. This is not at all possible. Unfortunately I do not have the private key for the public key address where my coins are as Jaxx wallet no longer shows me the same set of earlier public/private keys and transaction.
For most of my earlier transaction I have public and private key. Can I generate the 12 word mnemonic from the set of private/public keys just to confirm?

Sorry you can't invert a private key from a detached BIP 44 path to obtain a BIP 39 seed words. That is the mathematical nature of BIP 39 when combined with BIP 44.  However, Electrum seed words used by Monero are invertible from a Monero private key.


text:
How do I get my Bitcoin Core to rescan for a different wallet.dat file on OSX?
I have an old wallet.dat file that I have backed up and I have already replaced the new wallet.dat, which had no btc on it with the old one, which does. I have tried to enter the command for the rescan function to adapt to the different wallet information without success. Do I do this through the QT terminal or through the debug console command line? And can this be done before the bitcoin core wallet is completely synced with the entire network? Thanks.

The QT terminal (RPC) rescan option will be available in 0.16 (not release by the time of writing). https://github.com/bitcoin/bitcoin/pull/7061
Manual rescans should generally not be required, though, if you are missing transactions in an old wallet, the rescan may help.
In Core < 0.16 you need to rescan either by startup argument or by a configuration option.
Startup (OSX)
Open up "Terminal.app" and enter /Applications/Bitcoin-Qt.app/Contents/MacOS/Bitcoin-Qt --rescan
bitcoin.conf (OSX)
Place a plain text file called bitcoin.conf in ~/Library/Application Support/Bitcoin/ and make sure the textfile contains the line "rescan=1".
Make sure you remove the rescan=1 line after you have successfully rescanned your wallet.dat.


text:
Shapeshift + bitcoin cash question. The deposit link expired before the deposit reached it
At first, the transaction stayed unconfirmed, and then, four hours later, it had one confirmation, and now, two days later, the blockexplorer says it has 247 (?) confirmations, but the wallet still says it has two and is pending.  I figured that when the amount will reach Shapeshift, they will issue an automatic refund although the blockchair says that the main part of the deposit is already sent and spent. I tried to use CPFP while it was still unconfirmed to draft the funds back, but it seems like I misunderstood the function. Can anybody tell me what's the problem, if it's stuck for centuries or how to speed it up? And it is actually a second time in a row I get into this situation. Anyway, would anybody just sort out my confusion?
41cd7bb49bab97d82063f5fde1b2e5b9e8cb2cbc1faba65a938d70c69dbce8a7

What is "the wallet" in your question?

See also Why is my transaction not getting confirmed and what can I do about it?

the blockexplorer says it has 247 (?) confirmations, but the wallet still says it has two and is pending.

Sounds like an issue with the wallet not an issue with the transaction. Indeed, the transaction has many confirmations now, contact the support for the wallet you are using to see what the issue is (or ensure your wallet is fully synced if you are using a local wallet).

I figured that when the amount will reach Shapeshift, they will issue an automatic refund although the blockchair says that the main part of the deposit is already sent and spent.

Why would you get a refund if you are just depositing the funds?

I tried to use CPFP while it was still unconfirmed to draft the funds back, but it seems like I misunderstood the function.

If you sent the funds to an address shapeshift owns, only they can spend that transaction, so only they can use CPFP. But CPFP is unnecessary here because the transaction is confirmed now, as you mentioned.

Can anybody tell me what's the problem, if it's stuck for centuries or how to speed it up? And it is actually a second time in a row I get into this situation. Anyway, would anybody just sort out my confusion?

What makes you think it is stuck? The transaction was successful, if your account hasn't been credited in shapeshift then you will need to contact their support.

I guess I didn't make clear what happened: the time for the deposit on an exchange operation expired before the funds from my side got to the address. Thanks a lot though. I downloaded the newest version of the electron cash and it all shows up there. They actually made the refund 2 hours after the failure to deposit.

@Sokol66 glad to hear :) If the problem is resolved it would be great if you could mark the question as answered btw


text:
How do i transfer Bitcoins from Bitcoin Core to BitGo?
How do i send my BitCoins from Bitcoin Core to BitGo?


text:
Are there performance implications using the "timestamp" property of ImportMulti in the following way?
Based on the Developer Reference for importmulti, it seems the the timestamp property is purely used to determine how far back to rescan. If I have, say, 100 addresses and I simply set all of their timestamps to the same value (the earliest known timestamp), does this have any performance impact compared to setting each address' timestamp uniquely?
If the answer is no, then I'm wondering why this property was implemented as opposed to having a 3rd parameter holding a single "timestamp" for the entire list of addresses.

importmulti finds the earliest of the timestamps, and rescans from that point after all imports are done, yes. The wallet stores metadata about keys including the timestamp, which is why a timestamp is provided individually for each address rather than a single timestamp overall. Other commands like dumpwallet export a timestamp per key as well so this makes sense to provide it per-key when importing too, to save you having to look for the earliest before passing them in.

So, essentially the timestamp is used for ordering the list?

@MaxVernon No need to order them, just start rescanning from the earliest, because in doing so you'll encounter all of them :)

That makes sense. I can see how the timestamp can be a useful piece of info.  Thanks for the answer.


text:
Can encrypted private keys (BIP-38) be generated from HD wallets (BIP-32)?
I am aware that the introduction of BIP-38 resulted in a standard for passphrase-based encrypted private keys utilizing AES. What is not clear to me is whether these can be generated from HD wallets? Are the HD wallet seed-based private keys, then, considered encrypted private keys? Or do they follow the general private key format, since they are derived through their own HD wallets' processes?

The private keys themselves can be generated with BIP 32 and then those private keys encrypted. Private keys generated with BIP 32 are not special private keys; they are just normal private keys and you can do exactly the same things to those private keys as you would to any other private key.

Right, but do most modern HD wallets support this? It seems as though BIP-32 combined with BIP-39 (the optional passphrase that can be used when creating your HD wallet seed) is seen as an alternative. Would it be possible to BIP-38 encrypt the seed-generated master and child private keys? I cannot seem to figure out how to do this on top of HD-seeded private keys.

No, nearly all HD wallets do not use BIP 38 encryption. They still store the seed and all of your private keys in an encrypted format local to that wallet only. That encryption scheme is only used in the wallet software's wallet files and not to be read by others. BIP 39 is used because it creates more memorable strings. The seed phrase is generally supposed to be unencrypted to protect against the most common coin loss reason: forgetting the passphrase.

I see! So are all private keys generated from HD wallets not intended to be shared with other people? What if I wanted to share a child-derived private key to another party? With BIP-38 paper wallets these could be mailed and the passphrase shared through email or something. How is this functionality supported in HD wallets then?

Private keys are never intended to be shared with other people. You should never share a private key with someone. You can share a child private key in exactly the same way you share any other private key. As I said in my answer, there is nothing special about BIP 32 derived private keys. You can use BIP 38 encryption with a child private key. Note that if you did not use hardened derivation and the party you shared the child private key with also learns of your master public key, then your master private key can be derived and ALL of your child private keys derived thus resulting in coin loss


text:
How do premined coins work?
How does the concept of premining coins work?
For example, bitcoin gold is said to have 16,000 blocks premined. Well, at the current block reward of 12.5 bitcoins, 16000*12.5= 200,000 coins will premined for the developers which sounds sort of like a scam to me.
Anyways, how is this possible? Miners get rewarded for transactions they process. How do coins get premined on future blocks before being released?

Those are called "pump and dump" schemes. First you own a large amount of coins, then you make your coins public and try to convince everyone to use your coin, so its value will rise and you'll be rich.

... sort of like a scam to me

Well, a rumor that says Satoshi owns 1M Bitcoins (Source)

... how is this possible?

Bitcoin Gold will change the PoW to a GPU algorithm. Thus, the difficulty will start at "one" or so. Hence generating coins will be easy until the difficulty adjustment happens.

How do coins get premined on future blocks before being released

Again, first they'll mine, then they'll make it public.

I guess, but the key different is 1,000,000 at the time was not worth much, they haven't been moved for years (I assume he would of sold them when BTC first hit $1k if it was a scam), and the private key seems to be lost. BTC gold is intentionally is pre-mining 200,000 coins in the hope it will be worth something.

Pre-mined blocks is really more like saying the ledger is started with X coins already assigned to a particular address(es). This is very common for an ICO where the company wants to retain coins for future sales, to distribute as promotion or salary, or as part of the bonus for the founders / pre-investors.
They're called pre-mined because typically coins would need to be mined to be introduced to the ledger, and these are introduced before any mining has even begun. In most cases, coins that are distributed as part of the ICO are not included in the pre-mined numbers.


text:
Telegram channels can pump a coin by 50%-200%
I ran into couple of this channels on Telegram (it's an encrypted messaging software like whatsapp)
I joined a couple of them after a friend advised me and said there are channel who are giving signals on specific coins, and making them jump by hundreds of percentage in a few minutes,
how is this possible? If it's that easy to make profits on those altcoins why doesn't everybody doing it?
Just as an exemple, one of them is t.me/whaletank and http://affiliateceo.blogspot.com/ , most promising so far.
Can someone recommend me on few others to check out? I don't even know where i can search for more of this kind of groups, but I'm sure there are more..
I would like to join any kind of a large group with 1000+ people on it, I find it the best way to make profits right now when the whole market just keep crashing.

I'm voting to close this question as off-topic because
both recommendations and investment advice are off-topic here.

Most of these so called pump and dump groups are illegitimate or downright scams.
They usually only work for the inner group and the promoters who want to get you to join.
The scam works by buying the coin a few days earlier and then announce that you should buy the coin at a later time...the people like you try to buy the coins and then the promoters dump the coins at the high prices. By the time you buy it is too late unless you can sell instantly.
You have to think, if this was a real way of doing things then everyone would do this!


text:
Why is the root seed of an HD wallet undergo an additional HMAC-SHA512 hash to generate the master private key and master chain code?
From what I understand, the wallet seed is created by inputting into PBKDF2 (using HMAC-SHA512 of which 2048 rounds are applied) a bunch of mnemonic code words and an optional salt (defaulted to "mnemonic").  This generates a 512 bit-seed that is completely impractical to brute-force. This is a picture of the process that I am referring to taken from Mastering Bitcoin. Why, then, is it again hashed using HMAC-SHA512, besides for creating 512 bits of output (in the case where it originally might have been 128 or 256)? Why not just use a SHA512 hash alone (assuming the reason is just to create 512 bits)? What is the point of the HMAC here? Length-extension attacks should have been avoided from the previous iterations during PBKDF2, no?

It is because the root seed may not be 512 bits, it could be 128 bits or 256 bits for example as seen in the picture you linked. Thus the final SHA-512 is applied to the seed so that no matter what the seed is, 512 bits will always be generated.
The seed generation described in BIP 39 is independent of the seed -> extended private key step in BIP 32. I expect BIP 32 uses HMAC-SHA-512 instead of just SHA-512 because it makes no assumptions about how the seed was generated, and wants to ensure that the extended private key is uniquely generated for BIP 32 use rather than just using any old SHA-512 hash that could have come from elsewhere.

But why HMAC-SHA-512 as opposed to a regular SHA-512 hash? Was this just arbitrary since it was used before?

Ah sorry I misread your question. I've updated my answer :)

Can you explain why HMAC-SHA-512 makes no assumptions on how the seed was generated but SHA does?

Simply mean we want a key generated from the seed specifically for this purpose, rather than any old SHA-512 hash


text:
Encountering “ReadBlockFromDisk: Errors in block header at CBlockDiskPos(nFile=0, nPos=8)” error when I ran modified litecoin chainparams.cpp
First: I am a newbite to altcoin development, next to generate an altcoin from litecoin,
1- I have made a clone of litecoin using git clone https://githubcom/litecoin-project/lotecoin.git
2- I changed some of chain and coin parameters in chainparams.cpp as below:
// Copyright (c) 2010 Satoshi Nakamoto
 // Copyright (c) 2009-2015 The Bitcoin Core developers
 // Distributed under the MIT software license, see the accompanying
 // file COPYING or http://www.opensource.org/licenses/mit-license.php.

 #include "chainparams.h"
 #include "consensus/merkle.h"

 #include "tinyformat.h"
 #include "util.h"
 #include "utilstrencodings.h"

 #include <assert.h>

 #include "chainparamsseeds.h"
 #include "arith_uint256.h"

 static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
 {
     CMutableTransaction txNew;
     txNew.nVersion = 1;
     txNew.vin.resize(1);
     txNew.vout.resize(1);
     txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
     txNew.vout[0].nValue = genesisReward;
     txNew.vout[0].scriptPubKey = genesisOutputScript;

     CBlock genesis;
     genesis.nTime    = nTime;
     genesis.nBits    = nBits;
     genesis.nNonce   = nNonce;
     genesis.nVersion = nVersion;
     genesis.vtx.push_back(MakeTransactionRef(std::move(txNew)));
     genesis.hashPrevBlock.SetNull();
     genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
     return genesis;
 }

 /**
  * Build the genesis block. Note that the output of its generation
  * transaction cannot be spent since it did not originally exist in the
  * database.
  *
  * CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, *nNonce=2083236893, vtx=1)
  *   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
  *     CTxIn(COutPoint(000000, -1), coinbase *04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420**666f722062616e6b73)
  *     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
  *   vMerkleTree: 4a5e1e
  */

 static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
 {
     const char* pszTimestamp = "Tehran Times, Stonica wins finally";
     const CScript genesisOutputScript = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
     return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
 }

 void CChainParams::UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
 {
     consensus.vDeployments[d].nStartTime = nStartTime;
     consensus.vDeployments[d].nTimeout = nTimeout;
 }

 /**
  * Main network
  */
 /**
  * What makes a good checkpoint block?
  * + Is surrounded by blocks with reasonable timestamps
  *   (no blocks before with a timestamp after, none after with
  *    timestamp before)
  * + Contains no strange transactions
  */

 class CMainParams : public CChainParams {
 public:
     CMainParams() {
         strNetworkID = "main";
         consensus.nSubsidyHalvingInterval = 840000;
         consensus.BIP34Height = 710000;
         consensus.BIP34Hash = uint256S("00000000b2c50d03d4d0bdd38681775ce522f137518145d6b3c913b7dd4423e5");
         consensus.BIP65Height = 918684; // bab3041e8977e0dc3eeff63fe707b92bde1dd449d8efafb248c27c8264cc311a
         consensus.BIP66Height = 811879; // 7aceee012833fa8952f8835d8b1b3ae233cd6ab08fdb27a771d2bd7bdc491894
         consensus.powLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
         consensus.nPowTargetTimespan = 3.5 * 24 * 60 * 60; // 3.5 days
         consensus.nPowTargetSpacing = 2.5 * 60;
         consensus.fPowAllowMinDifficultyBlocks = false;
         consensus.fPowNoRetargeting = false;
         consensus.nRuleChangeActivationThreshold = 6048; // 75% of 8064
         consensus.nMinerConfirmationWindow = 8064; // nPowTargetTimespan / nPowTargetSpacing * 4
         consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
         consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
         consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008

         // Deployment of BIP68, BIP112, and BIP113.
         consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
         consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1485561600; // January 28, 2017
         consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1517356801; // January 31st, 2018

         // Deployment of SegWit (BIP141, BIP143, and BIP147)
         consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
         consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1485561600; // January 28, 2017
         consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1517356801; // January 31st, 2018

         // The best chain should have at least this much work.
         consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000000ba50a60f8b56c7fe0");

         // By default assume that the signatures in ancestors of this block are valid.
         consensus.defaultAssumeValid = uint256S("0x29c8c00e1a5f446a6364a29633d3f1ee16428d87c8d3851a1c570be8170b04c2"); //1259849

         /**
          * The message start string is designed to be unlikely to occur in normal data.
          * The characters are rarely used upper ASCII, not valid as UTF-8, and produce
          * a large 32-bit integer with any alignment.
          */
         pchMessageStart[0] = 0x0b;
         pchMessageStart[1] = 0xd0;
         pchMessageStart[2] = 0xb6;
         pchMessageStart[3] = 0xdb;
         nDefaultPort = 9335;
         nPruneAfterHeight = 100000;
 //static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
         genesis = CreateGenesisBlock(1511279793, 1251189192, 0x1d00ffff , 1, 50 * COIN);
         consensus.hashGenesisBlock = genesis.GetHash();

 /*
         // calculate Genesis Block
         // Reset genesis
         consensus.hashGenesisBlock = uint256S("0x");
         std::cout << std::string("Begin calculating Mainnet Genesis Block:\n");
         if (true && (genesis.GetHash() != consensus.hashGenesisBlock)) {
             LogPrintf("Calculating Mainnet Genesis Block:\n");
             arith_uint256 hashTarget = arith_uint256().SetCompact(genesis.nBits);
             uint256 hash;
             genesis.nNonce = 0;
             // This will figure out a valid hash and Nonce if you're
             // creating a different genesis block:
             // uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256();
             // hashTarget.SetCompact(genesis.nBits, &fNegative, &fOverflow).getuint256();
             // while (genesis.GetHash() > hashTarget)
             while (UintToArith256(genesis.GetHash()) > hashTarget)
             {
                 ++genesis.nNonce;
                 if (genesis.nNonce == 0)
                 {
                     LogPrintf("NONCE WRAPPED, incrementing time");
                     std::cout << std::string("NONCE WRAPPED, incrementing time:\n");
                     ++genesis.nTime;
                 }
                 if (genesis.nNonce % 10000 == 0)
                 {
                     LogPrintf("Mainnet: nonce %08u: hash = %s \n", genesis.nNonce, genesis.GetHash().ToString().c_str());
                     // std::cout << strNetworkID << " nonce: " << genesis.nNonce << " time: " << genesis.nTime << " hash: " << genesis.GetHash().ToString().c_str() << "\n";
                 }
             }
             std::cout << "Mainnet ---\n";
             std::cout << "  nonce: " << genesis.nNonce <<  "\n";
             std::cout << "   time: " << genesis.nTime << "\n";
             std::cout << "   hash: " << genesis.GetHash().ToString().c_str() << "\n";
             std::cout << "   merklehash: "  << genesis.hashMerkleRoot.ToString().c_str() << "\n";
             // Mainnet --- nonce: 296277 time: 1390095618 hash: 000000bdd771b14e5a031806292305e563956ce2584278de414d9965f6ab54b0
         }
         std::cout << std::string("Finished calculating Mainnet Genesis Block:\n");

 */

 //printf("%s\n",consensus.hashGenesisBlock.Tostring().c_str());
  std::cout << std::string("ENTER:\n");
        assert(consensus.hashGenesisBlock == uint256S("0x00000000b2c50d03d4d0bdd38681775ce522f137518145d6b3c913b7dd4423e5"));
         assert(genesis.hashMerkleRoot == uint256S("0xf8621e34b0dcd43361fe589702e06aa79992229bfbca57d058d8561635c30fbe"));
     std::cout << std::string("PASSED:\n");

         printf("min nBit:  %08x\n", consensus.powLimit);

         // Note that of those with the service bits flag, most only support a subset of possible options
         //vSeeds.emplace_back("seed-a.stonicacoin.loshan.co.uk", true);
         //vSeeds.emplace_back("dnsseed.thrasher.io", true);
         //vSeeds.emplace_back("dnsseed.stonicacointools.com", true);
         //vSeeds.emplace_back("dnsseed.stonicacoinpool.org", true);
         //vSeeds.emplace_back("dnsseed.koin-project.com", false);

         base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,127);
         base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,65);
         base58Prefixes[SCRIPT_ADDRESS2] = std::vector<unsigned char>(1,56);
         base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,176);
         base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x88, 0xB2, 0x1E};
         base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x88, 0xAD, 0xE4};

         vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));

         fDefaultConsistencyChecks = false;
         fRequireStandard = true;
         fMineBlocksOnDemand = false;

         checkpointData = (CCheckpointData) {
             {
                 {  0, uint256S("0x00000000b2c50d03d4d0bdd38681775ce522f137518145d6b3c913b7dd4423e5")},

             }
         };

         chainTxData = ChainTxData{
             // Data as of block db42d00d824950a125f9b08b6b6c282c484781562fa8b3bd29d6ce4a2627c348 (height 1259851).
             1502955334, // * UNIX timestamp of last known number of transactions
             1,  // * total number of transactions between genesis and that timestamp
                     //   (the tx=... number in the SetBestChain debug.log lines)
             0.00     // * estimated number of transactions per second after that timestamp
         };
     }
 };

 /**
  * Testnet (v3)
  */
 class CTestNetParams : public CChainParams {
 public:
     CTestNetParams() {
         strNetworkID = "test";
         consensus.nSubsidyHalvingInterval = 840000;
         consensus.BIP34Height = 76;
         consensus.BIP34Hash = uint256S("8075c771ed8b495ffd943980a95f702ab34fce3c8c54e379548bda33cc8c0573");
         consensus.BIP65Height = 76; // 8075c771ed8b495ffd943980a95f702ab34fce3c8c54e379548bda33cc8c0573
         consensus.BIP66Height = 76; // 8075c771ed8b495ffd943980a95f702ab34fce3c8c54e379548bda33cc8c0573
         consensus.powLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
         consensus.nPowTargetTimespan = 3.5 * 24 * 60 * 60; // 3.5 days
         consensus.nPowTargetSpacing = 2.5 * 60;
         consensus.fPowAllowMinDifficultyBlocks = true;
         consensus.fPowNoRetargeting = false;
         consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains
         consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
         consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
         consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
         consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008

         // Deployment of BIP68, BIP112, and BIP113.
         consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
         consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1483228800; // January 1, 2017
         consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1517356801; // January 31st, 2018

         // Deployment of SegWit (BIP141, BIP143, and BIP147)
         consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
         consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1483228800; // January 1, 2017
         consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1517356801; // January 31st, 2018

         // The best chain should have at least this much work.
         consensus.nMinimumChainWork = uint256S("0x0000000000000000000000000000000000000000000000000000364b0cbc3568");

         // By default assume that the signatures in ancestors of this block are valid.
         consensus.defaultAssumeValid = uint256S("0xad8ff6c2f5580d2b50bd881e11312425ea84fa99f322bf132beb722f97971bba"); //153490

         pchMessageStart[0] = 0xfd;
         pchMessageStart[1] = 0xd2;
         pchMessageStart[2] = 0xc8;
         pchMessageStart[3] = 0xf1;
         nDefaultPort = 19335;
         nPruneAfterHeight = 1000;

         genesis = CreateGenesisBlock(1511279793, 0, 0x1d00ffff , 1, 50 * COIN);
         consensus.hashGenesisBlock = genesis.GetHash();
         //assert(consensus.hashGenesisBlock == uint256S("0x"));
         //assert(genesis.hashMerkleRoot == uint256S("0x"));

         vFixedSeeds.clear();
         vSeeds.clear();
         // nodes with support for servicebits filtering should be at the top
         //vSeeds.emplace_back("testnet-seed.stonicacointools.com", true);
         //vSeeds.emplace_back("seed-b.stonicacoin.loshan.co.uk", true);
         //vSeeds.emplace_back("dnsseed-testnet.thrasher.io", true);

         base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111);
         base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
         base58Prefixes[SCRIPT_ADDRESS2] = std::vector<unsigned char>(1,58);
         base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,239);
         base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF};
         base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94};

         vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));

         fDefaultConsistencyChecks = false;
         fRequireStandard = false;
         fMineBlocksOnDemand = false;

         checkpointData = (CCheckpointData) {
             {
                 {0, uint256S("")},
             }
         };

         chainTxData = ChainTxData{
             // Data as of block 3351b6229da00b47ad7a8d7e1323b0e2874744b5296e3d6448293463ab758624 (height 153489)
             //1502953751,
             //382986,
             //0.01
         };

     }
 };

 /**
  * Regression test
  */
 class CRegTestParams : public CChainParams {
 public:
     CRegTestParams() {
         strNetworkID = "regtest";
         consensus.nSubsidyHalvingInterval = 150;
         consensus.BIP34Height = 100000000; // BIP34 has not activated on regtest (far in the future so block v1 are not rejected in tests)
         consensus.BIP34Hash = uint256();
         consensus.BIP65Height = 1351; // BIP65 activated on regtest (Used in rpc activation tests)
         consensus.BIP66Height = 1251; // BIP66 activated on regtest (Used in rpc activation tests)
         consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
         consensus.nPowTargetTimespan = 3.5 * 24 * 60 * 60; // two weeks
         consensus.nPowTargetSpacing = 2.5 * 60;
         consensus.fPowAllowMinDifficultyBlocks = true;
         consensus.fPowNoRetargeting = true;
         consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
         consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016)
         consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
         consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;
         consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL;
         consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
         consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0;
         consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL;
         consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
         consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 0;
         consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 999999999999ULL;

         // The best chain should have at least this much work.
         consensus.nMinimumChainWork = uint256S("0x00");

         // By default assume that the signatures in ancestors of this block are valid.
         consensus.defaultAssumeValid = uint256S("0x00");

         pchMessageStart[0] = 0xfa;
         pchMessageStart[1] = 0xbf;
         pchMessageStart[2] = 0xb5;
         pchMessageStart[3] = 0xda;
         nDefaultPort = 19444;
         nPruneAfterHeight = 1000;

         genesis = CreateGenesisBlock(1511279793, 0, 0x1d00ffff , 1, 50 * COIN);
         consensus.hashGenesisBlock = genesis.GetHash();
         assert(consensus.hashGenesisBlock == uint256S("0x9"));
         assert(genesis.hashMerkleRoot == uint256S("0x"));

         vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds.
         vSeeds.clear();      //!< Regtest mode doesn't have any DNS seeds.

         fDefaultConsistencyChecks = true;
         fRequireStandard = false;
         fMineBlocksOnDemand = true;

         checkpointData = (CCheckpointData) {
             {
                 {0, uint256S("530827f38f93b43ed12af0b3ad25a288dc02ed74d6d7857862df51fc56c416f9")},
             }
         };

         chainTxData = ChainTxData{
             0,
             0,
             0
         };

         base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111);
         base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
         base58Prefixes[SCRIPT_ADDRESS2] = std::vector<unsigned char>(1,58);
         base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,239);
         base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF};
         base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94};
     }
 };

 static std::unique_ptr<CChainParams> globalChainParams;

 const CChainParams &Params() {
     assert(globalChainParams);
     return *globalChainParams;
 }

 std::unique_ptr<CChainParams> CreateChainParams(const std::string& chain)
 {
     if (chain == CBaseChainParams::MAIN)
         return std::unique_ptr<CChainParams>(new CMainParams());
     else if (chain == CBaseChainParams::TESTNET)
         return std::unique_ptr<CChainParams>(new CTestNetParams());
     else if (chain == CBaseChainParams::REGTEST)
         return std::unique_ptr<CChainParams>(new CRegTestParams());
     throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
 }

 void SelectParams(const std::string& network)
 {
     SelectBaseParams(network);
     globalChainParams = CreateChainParams(network);
 }

 void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
 {
     globalChainParams->UpdateVersionBitsParameters(d, nStartTime, nTimeout);

As you may know the bitcoin developers has omitted the genesis block mining code from source code published in github, but I fortunately found some piece of code in related blogs and it worked, then I have calculated the new Genesis hash, Merkelroot hash and Nonce and put into code as you can see above. The code was compiled correctly and I have not received Assertion failed message for Genesis block but I received another error which you can see in debug.log as below:
    2017-12-15 07:31:33

 2017-12-15 07:31:33 Stonicacoin version v0.15.0.1-gba8ed3a93be
 2017-12-15 07:31:33 InitParameterInteraction: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1
 2017-12-15 07:31:33 Assuming ancestors of block 29c8c00e1a5f446a6364a29633d3f1ee16428d87c8d3851a1c570be8170b04c2 have valid signatures.
 2017-12-15 07:31:33 Using the 'standard' SHA256 implementation
 2017-12-15 07:31:33 Using RdRand as an additional entropy source
 2017-12-15 07:31:33 Default data directory /home/kevin/.stonicacoin
 2017-12-15 07:31:33 Using data directory /home/kevin/.stonicacoin
 2017-12-15 07:31:33 Using config file /home/kevin/.stonicacoin/stonicacoin.conf
 2017-12-15 07:31:33 Using at most 125 automatic connections (1024 file descriptors available)
 2017-12-15 07:31:33 Using 16 MiB out of 32/2 requested for signature cache, able to store 524288 elements
 2017-12-15 07:31:33 Using 16 MiB out of 32/2 requested for script execution cache, able to store 524288 elements
 2017-12-15 07:31:33 Using 8 threads for script verification
 2017-12-15 07:31:33 scheduler thread start
 2017-12-15 07:31:33 HTTP: creating work queue of depth 16
 2017-12-15 07:31:33 No rpcpassword set - using random cookie authentication
 2017-12-15 07:31:33 Generated RPC authentication cookie /home/kevin/.stonicacoin/.cookie
 2017-12-15 07:31:33 HTTP: starting 4 worker threads
 2017-12-15 07:31:33 Cache configuration:
 2017-12-15 07:31:33 * Using 2.0MiB for block index database
 2017-12-15 07:31:33 * Using 8.0MiB for chain state database
 2017-12-15 07:31:33 * Using 440.0MiB for in-memory UTXO set (plus up to 4.8MiB of unused mempool space)
 2017-12-15 07:31:33 init message: Loading block index...
 2017-12-15 07:31:33 Opening LevelDB in /home/kevin/.stonicacoin/blocks/index
 2017-12-15 07:31:33 Opened LevelDB successfully
 2017-12-15 07:31:33 Using obfuscation key for /home/kevin/.stonicacoin/blocks/index: 0000000000000000
 2017-12-15 07:31:33 LoadBlockIndexDB: last block file = 0
 2017-12-15 07:31:33 LoadBlockIndexDB: last block file info: CBlockFileInfo(blocks=0, size=0, heights=0...0, time=1970-01-01...1970-01-01)
 2017-12-15 07:31:33 Checking all blk files are present...
 2017-12-15 07:31:33 LoadBlockIndexDB: transaction index disabled
 2017-12-15 07:31:33 Initializing databases...
 2017-12-15 07:31:33 Pre-allocating up to position 0x1000000 in blk00000.dat
 2017-12-15 07:31:33 Opening LevelDB in /home/kevin/.stonicacoin/chainstate
 2017-12-15 07:31:33 Opened LevelDB successfully
 2017-12-15 07:31:33 Wrote new obfuscate key for /home/kevin/.stonicacoin/chainstate: 77f259e28117a4e1
 2017-12-15 07:31:33 Using obfuscation key for /home/kevin/.stonicacoin/chainstate: 77f259e28117a4e1
 2017-12-15 07:31:33 init message: Rewinding blocks...
 2017-12-15 07:31:33  block index              11ms
 2017-12-15 07:31:33 No wallet support compiled in!
 2017-12-15 07:31:33 ERROR: ReadBlockFromDisk: Errors in block header at CBlockDiskPos(nFile=0, nPos=8)
 2017-12-15 07:31:33 *** Failed to read block
 2017-12-15 07:31:33 Error: Error: A fatal internal error occurred, see debug.log for details

I found that this error(eg. ERROR: ReadBlockFromDisk: Errors in block header at CBlockDiskPos(nFile=0, nPos=8) ) occur in CheckProofOfWork function which is in pow.cpp, Any recommendation is appreciated.

You can take a look here ERROR: ReadBlockFromDisk: Errors in block header at CBlockDiskPos(nFile=0, nPos=8). It may help you get to the bottom of your issue.

You need to mine your own Genesis block. See a guide to do that here:
https://medium.com/@dophuoc/how-to-mine-a-genesis-block-for-your-bitcoin-fork-471b1fb47efb


text:
Why is there no decentralized Bitcoin trading API?
Since nobody has answered me the last 30 times when I asked for decentralized Bitcoin trading APIs, I can pretty safely conclude that it just doesn't exist. So that's why I now ask why this is.
Don't you think it's ironic that Bitcoin, the decentralized currency, has no means of trading it with other cryptocurrencies, or with some kind of token, or with fiat, or in any way, without using one of those centralized "exchanges" which all force you to give up privacy completely and send them photo id of government ids and stuff like that?
It should go without saying that such centralized exchanges, with their "KYC/AML" demands, defeat the entire point of Bitcoin -- to not be harassed in this manner. Many of us cannot even do it, even if we wanted, because we simply don't have any "photo ids" from the government and have no interest in getting any.
I know about Bisq. It's the only decentralized "exchange" for Bitcoin-fiat that I know of. It has only a read-only API, meaning you cannot actually trade with it. The progress of their API seems to be zero since years and years when they started talking about it. I'm not holding my breath and believe that it could very well never be released.
For this reason, I ask you: Why is there no such thing as a decentralized Bitcoin API? Bisq apparently can stay around for manual use, so it can't be "illegal".
You'd think with all this money in circulation and all these countless marketplaces for cryptocurrencies, there would at least be one small project which give you the ability to script-trade Bitcoin! It's maddening to me that there is no such thing from the looks of it. I have searched for countless hours but nothing is found in search engines and nobody answers whenever I ask them on IRC or Stack sites.
Please at least give me a good reason why this is. Normally, there is at least some logical explanation for things. In this case, it's just utterly baffling to me.

There's no profit in a truly decentralized exchange, so there's not much incentive for people to do the extensive, difficult development and maintenance. The "best minds" of crypto couldn't even secure The DAO which was a much simpler project.

I'd say that's just because nobody programmed it. Bisq community for example is short on programmers so they concentrate on the essentials. Companies have no interest in the development or shy away from the legal risk, where they are increasingly forced to perform financial police duties similar like banks (KYC/AML). Hopefully the Bisq DAO brings enough funds to have developers paid for this kind of work.
Another concern is security. Successful replay or DOS attacks or any essential coding error might risk the whole Bisq project. Like with Bitcoin it's not easy to force the users to upgrade to latest version in case of malicious code.
Do you know the latest developments at the Bisq API? Have a look at this developer conference. There is as well a slack channel for the Bisq API interested.
Record of Bisq developers API discussion, Sept 2019


text:
How to get concerned specific unspent(coin selection algorithm) from list of unspents in a wallet to calculate transaction size
I have a problem to calculate dynamic transaction fees. The problem which i am facing is to calculate the transaction size.
When i have one unspent in my wallet it is too easy to calculate transaction size. but when there are multiple unspents in wallet i think then there is some coin selection algorithm to calculate the best unspent or combination of unspents.
I have compiled document
 document  that explains this problem completely.
I need opinion in which way i wanna move? whether to develop own coin selection algorithm or there are some other options exist?

What exactly are you trying to calculate the size for? To calculate the transaction fee before coin selection? During selection? Or after?

In a simple words i just want to get the size of transaction which i am going to broadcast. When i got the size then i will calculate transaction fees.

If you just want to see the transaction fee before it is broadcast, use the raw transaction api (createrawtranscation,fundrawtransaction, etc.) or the psbt api (walletcreatefundedpsbt,walletprocesspsbt,etc.) and make the transaction. Then inspect it before you broadcast it.

I have done by using https://github.com/bitcoinjs/coinselect


text:
XPub to YPub Converter (python) - Last digits wrong
The code below is generating an YPub from XPub with the last 6 digits wrong.
How can I verify what's happening and fix this error?
e.g.:
It should be  ypub6X7aFbqxwbJHJQqUhfTEZDWxVT8qbu4qjN8fCz9ADRuAwaZQ243YiB1w5yTE2qRJzRJ3Kza9DbefU8pnqjk3GEmn6g9usvkZZrP94VcBVdz
but it returns ypub6X7aFbqxwbJHJQqUhfTEZDWxVT8qbu4qjN8fCz9ADRuAwaZQ243YiB1w5yTE2qRJzRJ3Kza9DbefU8pnqjk3GEmn6g9usvkZZrP94YkSjSS
The code is adapted from this function in JS, that works well.
import hashlib
import base58

prefixesPub =  {
  'xpub': '0488b21e',
  'ypub': '049d7cb2',
  'Ypub': '0295b43f',
  'zpub': '04b24746',
  'Zpub': '02aa7ed3',
  'tpub': '043587cf',
  'upub': '044a5262',
  'Upub': '024289ef',
  'vpub': '045f1cf6',
  'Vpub': '02575483'
}

def convert_pub_key(_xpub, target_prefix):
  decoded_extended_publicKey = base58.b58decode(_xpub.strip())
  extended_public_key_no_prefix = decoded_extended_publicKey[4:]
  extended_public_key_new_prefix = bytes.fromhex(prefixesPub[target_prefix]) + extended_public_key_no_prefix
  print(base58.b58encode(extended_public_key_new_prefix))

pub_key = "xpub6CHJwwB3nukoT7eMsJfcM8RTKUzPfH5LpFcSRbFGqRXHtUkAmPsz67Mo4mVe2vmPanBEaWyakwJ7arDE83L2U16BELTVJ1w5J8KVfyMqtzE"
prefix = "ypub"
convert_pub_key(pub_key, prefix)

The base58.b58decode and base58.b58encode functions only do the Base 58 decode/encode. However xpubs are encoded with Base 58 Check encoding. The difference is that Base 58 Check encoding computes a checksum of the payload and appends the first 4 bytes of that to the payload before the base 58 encoding.
You need to be using base58.b58decode_check and base58.b58encode_check which will drop the checksum for the decode, and add the checksum for the encode.


text:
Can I use same WIF/privkey to make myself a segwit address?
I think I know the answer, but want to make sure asking here.
I have my old privkey/WIF and some funds on associated legacy bitcoin address. Reading this code https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L50 I think I can make a segwit address out of my private key, transfer all funds to this segwit address, and I will still be able to use old private key to control those funds?
Thanks!

Yes.
If the P2SH-P2WPKH is implied (which is segwit reflection of plain old P2PKH like in your case), you still use one private key to derive a segwit address, and you still can reuse this private key to create a redeem script.
In fact, segwit address is derived from a redeem script.
But, there is a restriction, that unlike P2PKH, where you can use uncompressed and compressed public keys to create two separate addresses, in P2SH-P2WPKH, only compressed one must be used.
So, it is technically possible, given that you fully control address and transaction generation. Otherwise, it is on your wallet to give you such functionality.


text:
Why public Electrum servers serving on websocket (WS) are so rare?
Couldn't find a single one. Only TCP or TLS.
Am I looking in the wrong place? ( https://1209k.com/bitcoin-eye/ele.php?chain=btc )

They are rare because Electrum and all the other wallets using the protocol do not support it client-side, so nobody setting up an ElectrumX server has any incentive to enable this. ElectrumX requires you to enable individual protocols explicitly. Furthermore, as you can see in the changelog they have only been supported since May 2019.


text:
Is there a way to fetch all transactions in a block via electrum protocol?
Quickly surfing through the list of electrum methods, looks like not, and I will have to use getblock from bitcoind json-rpc.
Is there a better way?

Looping for all: blockchain.transaction.id_from_pos?

thanks @MCCCS that looks like what I need! is there a way to get how many transactions there are in a specific block (without iterating to some ridiculous value like 99999)?

No I don't think that's possible, you need to iterate (though you can check like 1,2,4,8,...512,1024) then binary bisect


text:
difference between pre-mining and mining
I am new in blockchain and not an IT person.
is there a difference between pre-mining a cryptocurrency and mining a block?
I do understand the rewarding action when a miner solves a hash puzzle to add a block to the chain.  However, I do not get the pre-mining activity.  Maybe I am mixing up 2 different functionalities.

Pre-mining means that new coins have been mined before the coin has been made public. Which means the creator of the new currency had an unfair advantage and started with a large amount of coins before anyone else had the chance.
Pre-mining often deters other people from joining and any currency is useless without users.


text:
Is it possible to forward signed transaction using bitcoind prune mode?
Summary:
Is it possible to perform createrawtranscation , signrawtransaction and sendrawtransaction rpc call using bitcoin in prune mode?
Detail :
I want to implement an API that performs p2p BTC transfer, and for this purpose, I don't want to run a full node in my AWS server as I have to buy extra space for this. I was exploring third-party applications but all of them are out of my budget. So I was curious if I could run prune mode BTC core to perform above mention RPC call?
I would be very thankful if you guys can give some advice as per my requirement.


text:
How to fetch all UTXO from a SPV wallet using bitcoin-filter.js (or other lib)?
I am using bitcoinjs-lib to create private key (WIF), addresses and sign the transactions.
I would like to fetch all transactions (UTXOs) associated with a wallet. I found these libs:  bitcoin-filter  and bitcoin-net .
But I didn't understand the code below:
var filter = new Filter(peers)
filter.add(new Buffer('818895f3dc2c178629d3d2d8fa3ec4a3f8179821', 'hex'))
filter.add(walletObject)

What parameters does filter receive ? Are they the addresses ?
If so, how can I find all the used addresses of a HD wallet ?

You are asking a few different questions here, I'll try to help with each:
Wallet filters: See BIP37 which describes SPV wallets in general. A Bloom Filter is generated by the SPV wallet and sent to full nodes on the network. The filter is a compact data structure that represents every public key the SPV wallet is interested in. The full node will check each transaction in blocks and the mempool against this filter and if there is a match, that transaction is sent back to the SPV wallet. BIP37 specifies all the data the filter is tested against but in summary, it includes transaction hashes, public keys, public key hashes, and script hashes.
You can see here in the bcoin wallet (also JavaScript) where the wallet's public key hashes and watched outpoints are added to the bloom filter.
The bcoin socket API also has a method for adding address hashes to a bloom filter before it is sent to a full node.
HD Wallet Addresses: To understand HD wallets it's important to read BIP44 which describes the recovery process. During BIP44 wallet recovery, the program starts with a seed of entropy (derived from your 12- or 24-word phrase). It then generates account 0, receive and change addresses 0 through 20. Then, starting from a specified block height (just before the wallet was first generated in time) it iterates through the blockchain looking for TXs that match those addresses. Every time it finds a match, it generates another address (the 21st address, and so on...). In SPV mode, each new address would have to be added to the Bloom Filter and sent back to the full node. This actually can cause issues with the wallet sync, and some blocks may need to be re-scanned.
Notes:

I am using bitcoinjs-lib to create private key (WIF), addresses and sign the transactions. I would like to fetch all transactions (UTXOs) associated with a wallet.

In general using a single private key and reusing a single address is considered bad practice. BIP44 is an excellent design for wallets that generate multiple keys and addresses.
If you really only have one address to scan for UTXO you can use an address indexer like in bcoin or soon-to-be-merged to Bitcoin Core. You may also have some success just using rpc scantxoutset fo your single address.


text:
How do I determine the descriptor of a given Extended Public Key?
I am trying to run the bitcoin-cli getdescriptorinfo on a ypub... extended public key. Every time I do this I receive the message:

error code: -5
error message:
Invalid descriptor

How can I determine the correct descriptor for a given ypub?
I am trying to derive the addresses using bitcoin core and import them into my wallet. I am fairly new to using bitcoin-core so I'm not even sure if this is the best way to do this. If not, what other method might I be able to use?

Possible duplicate of Why does importmulti not support zpub and ypub?

I don't have any other info other than the extended public key.

Someone could probably write a tool to convert ypubs and zpubs to descriptor format. I don't think such a tool exists.


text:
Bitcoin Core `getaddressesbyaccount` method not found (-32601)
On macOS Mojave I have a full bitcoin node synced using bitcoind.
I want to get the public address of the default account (i.e. the empty string "").
So I run bitcoin-cli getaddressesbyaccount "" but I get:
error code: -32601
error message:
Method not found

Version of bitcoind is: Bitcoin Core Daemon version v0.18.0.0-g2472733a24a9364e4c6233ccd04166a26a68cc65
Copyright (C) 2009-2019 The Bitcoin Core developers
And of bitcoin-cli is: Bitcoin Core RPC client version v0.18.0.0-g2472733a24a9364e4c6233ccd04166a26a68cc65
What's wrong?

The account API has been deprecated for a while, and was completely removed in Bitcoin Core 0.18.0.
You should be using the new mutliwallet API, or handling account based labelling externally.


text:
Best way to find list of UTXO related to xpub
Apparently the way to find a list of UTXO related to an xpub is to derive all addresses from the master private key and query a node with each and every one of them.
It is possible to generate 4294967296 addresses from a single extended key.
How should a wallet proceed to manage this in an efficient way?
I guess that in an ideal situation, addresses are generated in a sequential order... but my intuition tells me that nothing prevents a wallet from doing otherwise.

The balance checks are cut short based on a gap limit.
A gap limit is usually set to 20, and is defined as a consecutive block of addresses with no transactions.
Since HD wallets only give out a new address on explicit request, or automatically when the previously issued address has been used, it is assumed that someone will not leave a block of 20 consecutive addresses unused.
Wallet software will generate a short list of maybe addresses when you load an xpub or other form of seed. It will then check through that, and if it doesn't find 20 consecutive unused addresses, it will generate another short list (so the first list might cover 0-100, then 100-200, etc). until it finds the block of unused addresses.
This assumption naturally falls apart if you are running an exchange, payment service, or other wallet set up where it is very likely that you will have many hundreds of unused addresses. Those systems generally keep track of assigned addresses out of band, and have specialized indexer systems that can track many millions of addresses.

The software I am building is about keeping track of funds related to an xpub/ypub/zpub no matter the origin. My questioning is about the fact that nobody can prevent wallets from overriding the gap limit. Anybody can write one pretty easily. So I guess there is no totally reliable way to know how many funds are related to an xpub.

If you intend to deal with arbitrary xpubs, then yes, you have no choice but to check every address on every possible account in that xpub, which is not a viable approach (a single xpub will lead to many trillions of addresses). If you are only dealing with xpubs generated by other, sane wallets like electrum, ledger, trezor, etc. then the gap limit is a safe assumption

RooSoft, You're thinking of an xpub like an address, which it is not. It is a brute force issue if someone uses a random address deep in the chain. Fortunately no wallet software will use a random index so utilizing the gap limit approach is the most efficient way to check for UTXOs related to an xpub.

Not all wallets are the same, but a good wallet should always follow standards. A standard for address-generation generally accepted is BIP44. In this way, you could scan the first consecutive addresses that a BIP44-compliant wallet would create. If the wallet supports Segwit, then you should look at BIP49 and BIP84 as well.
As Raghav Sood pointed out in his answer, most wallets scan a certain amount of unused addresses before they decide to stop scanning for funds. Most of them use 20 as the gap limit (maximum gap in between unused addresses).
Now, to answer your question, you are totally right. Nothing prevents a wallet from not complying with BIP44 standard or with any other standard whatsoever. That is why it is important to know the wallet you are dealing with. However, a well defined protocol/standard helps with the fund-discovery process which is super important for any kind of wallet, for which it is almost certain that every wallet out there possesses a standard for address creation (either BIP44 or one of their own).
Just find out the standard that the wallet you're dealing with is following for address creation, and that would lead you to find the most efficient way to find the UTXO associated to the xpub.

Thing is the software being built is about tracking funds from any source the xpub is from without discrimination. I wanted to know if there is a sure way to track all funds without making billions of requests. What I have come to realize is that if a wallet goes beyond the 20 empty derivation gap, some actual wallets might not keep track of those extra UTXOs as we speak.

ah ok. Then, I guess the standards, as I mentioned, would work for most cases. And yes, you are right about the gap. Although, you are usually able to fix that number if you notice that the total of your funds is not being reflected. Take into account also the mechanics of wallets for address creation, and what are the odds of an address to be used beyond the 20 gap. In your case, if you want to make sure that you are scanning the total of the funds, then you can use a wider gap. It might seem too much, but that is the most efficient way for scanning. There is no other possible shortcut.

Thank you so much Oscar... helps increase confidence I have in what I am trying to do.