text:
How exchanges generate transactions for all cryptocurrencies and send it to their network nodes?
This is an important question for me, I know some Bitcoin wallets like blockchain.info are a Full Node, but exchanges which support so many coins, how do they create transactions per cryptocurrency? do they have a full node client for per cryptocurrency?
Just Bitcoin needs 170 GB space disk!
Are exchanges using third-party servers and apis?

For an exchange, 170GB is not a lot, at all. In fact, it's a laughably small amount. Even on an SSD (which is not necessary), the storage cost would be about $100. Big exchanges might make $1M in revenue every day. Operating a node (or ten) is a complete non-issue.
You seem to be thinking that if Bitcoin's blockchain is 170GB, then so are the others. But Bitcoin is the most popular cryptocurrency, and it has way more transactions than any other (with the possible exception of Ethereum, which is more wasteful and has high traffic due to the ICO hype). The blockchains for most cryptocurrencies are tiny in comparison, and the sum total storage shouldn't be more than, say, 1TB (again, tiny for any large business). A single machine could run nodes for all coins.
SPV clients (like Electrum for Bitcoin) offer a middle ground between running a full node, and relying completely on a 3rd party service.
Ultimately, every exchange decides how to set up its infrastructure. It might run a node. It might not. There's no real way to answer this in general, this is something which should be asked of each specific exchange.

Funding is the answer to your unasked question. A standard 10U blade server can hold 24 servers--you can fit 4 in a standard rack and still have room for a 150TB NAS and routing. A modest setup could be had for under 100k and could easily support full nodes of a hundred cryptocurrencies.
No reputable exchange would host their wallets, private keys, and critical customer data on 3rd party servers. There's just too much at stake.

The OP didn't ask about private keys (or customer data). You can use someone else's node while keeping the private keys yourself.

Again, that assumes a huge amount of risk while the upside is limited. I don't think any reputable exchange would rely on third party full nodes.


text:
Get real fee per transaction
I am trying to get real fee per trasnaction.
So I have an account whit balance 0.06940000 and have a second account with balance 0.00000000.
To get current fee I have run the command
bitcoin-cli getmempoolinfo

and got the mempoolminfee = 0.00001000.
I thought that when I send the 0.06939000 in my account rest balance will 0.00000000. but I got 0.00004860. Actually the fee was  0.0000514.
general question is WhY ?
Please tell me to understand how is fees working!

What getmempoolinfo is returning is not the minimum fee to send a transaction, but the minimum rate per kilobyte to send a transaction. Your bitcoin client will take the configured fee and multiply it by the size of the transaction in kilobytes to calculate the actual transaction fee.
The size of a transaction is somewhat difficult to compute (for a person) because it requires understanding the number of inputs that are required to fulfil the transaction, the number of outputs (primary recipients + change address), and the targeted transaction fee (since appropriate fees could eliminate the need for a change address).
There are online fee calculators out there you can use to estimate these, but it is still difficult to completely empty a wallet with a known fee using the straight bitcoin client.

Is there a way to get fee before sending transaction ?

No, but if all you are looking to do is empty a wallet, you can pass an argument to sendtoaddress which will take the fee out of the sent amount rather than the wallet you're sending from--you will receive less bitcoin than you "sent", but you will be able to empty the wallet.
See argument #5 for sendtoaddress: https://bitcoin.org/en/developer-reference#sendtoaddress

thanks! but what when i want to send bitcoins from specific account to address?

Again, if you want to remove a specific amount from the sending address, you set that 5th argument to true. If you want a specific amount to be received by the recipient address, you leave it set to false.

source: Stack Exchange

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

sort: votes


text:
Bitcoin sendfrom and sendtoaddress
I am using bitcoin daemon in my system to get and pass btc to users. So now I want to pass some btc to another users but I can not understand what is the difference between sendfrom and sendtoaddress. I have read about sendtoaddress command in
http://chainquery.com/bitcoin-api/sendtoaddress but could not understand where this btc is going from

According to the Bitcoin core developers reference, SendFrom is deprecated and you should use SendToAddress or SendMany instead.
Note that SendFrom sends from an account not from an address. The Account feature is being removed from Bitcoin core.
I assume the (HD) wallet rummages around for suitable UTXOs to use as inputs to the transaction.

Bitcoin node is one wallet and accounts are its internal accounting system which is deprecated now: https://github.com/bitcoin-dot-org/bitcoin.org/issues/1287
The major issue is account balance can go negative which is "WONTAFIX" https://github.com/bitcoin/bitcoin/issues/2079
I'd recommend using latest Bitcoin 0.17.0 which has multi wallet features which can isolate each user, further read:

https://en.bitcoin.it/wiki/API_reference_(JSON-RPC)#Multi-wallet_RPC_calls
https://github.com/bitcoin/bitcoin/pull/13058

Edit: (To upgrade from 0.16.3 to 0.17.0)
Assuming installed 0.16.3 via sudo apt-add-repository ppa:bitcoin/bitcoin I was able to upgrade from 0.16.3 to 0.17.0 successfully by following:

cd ~
wget https://bitcoincore.org/bin/bitcoin-core-0.17.0/bitcoin-0.17.0.tar.gz
tar -xvzf bitcoin-0.17.0.tar.gz
cd bitcoin-0.17.0/

#Install dependencies to compile

sudo apt-get update
sudo apt install build-essential libtool autotools-dev automake pkg-config libssl-dev libevent-dev bsdmainutils git libdb4.8-dev libdb4.8++-dev curl
sudo apt install build-essential libtool autotools-dev automake pkg-config libssl-dev libevent-dev bsdmainutils git libdb4.8-dev libdb4.8++-dev curl
sudo apt install libboost-system-dev libboost-filesystem-dev libboost-chrono-dev libboost-program-options-dev libboost-test-dev libboost-thread-dev libzmq3-dev

#Compile Bitcoin 0.17.0

./autogen.sh
./configure
make

#sudo worked for me

sudo make install

#rebooting was required for me as bitcoind was still showing 0.16.3, after reboot 0.17.0 was shown

thanks for reply! I have already installed 0.16.3 version. but i can't upgrade it to 0.17.0 . Can you send me more details to upgrade it ?

@YurGasparyan I added details as I tested to upgrade from 0.16.3 to 0.17.0

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


text:
Bitcoin core read-only
I have system where users can generate addresses and bring some coins, and get bonuses after. I want to make my core read-only. For this I have a second bitcoin core which have not connected to internet. So as I read I can change the MPK of my general core for the MPK of offline core. That is why the online core will be read-only.
Help me please to solve this problem!

You can add addresses to your "read-only" node as watch only addresses

How can I do that? Is this associated with extended mpk ?


text:
Can not indentify accounts
I am trying to get balance of accounts and when running bitcoin-cli listaccounts I am getting the data look like this
{
  "":0.81234545
}

I wanted to know what is the "" and 0.81234545 and where my real addresses.
Thanks!

Note: The accounts feature is being deprecated from the codebase. Accounts are groupings of addresses, constructed by the wallet software.
You may find that the listunspent or listreceivedbyaddress commands are more useful for you.

I wanted to know what is the "" and 0.81234545 and where my real addresses

"" is the default name of an account
0.81234545 is the balance of your wallet, in BTC.

I generated  more than 20 accounts. Waht do you mean saying default name of an account ?

Note that an account is not an address. An account is a group of addresses made by your wallet. For convenience, you can name the accounts you create. If you do not specify an account name, the default name is an empty string, "".

So but when I want to get balance of account , I am getting 0.0000 but bitcoin explorer site shows that balance of account is 0.12345667. Why ? )

In bitcoind, an account is different than an address. A bitcoin explorer site would not show you an account, it would show you an address. To show you one of your 'accounts', the explorer site would need to know which group of addresses to include, but only your wallet will know that info. Trying to compare the output of bitcoin-cli listaccounts with a block explorer site will not work in almost every case.


text:
How to find out as soon as possible about a transaction to my payment address?
I'm running an online store. I added the option to pay using bitcoin, using Mycelium Gear.
Gear can be configured to wait for 0-6 confirmations and up to 48*60*60 seconds from the moment the payment address was generated for a transaction to be paid/confirmed.
There are three potentially interesting moments in the life of a transaction when someone might like to be notified:

A transaction with an output that is being watched has been transmitted on the p2p network.
The transaction has been included in a block.
The transaction is fully confirmed (is 6 blocks deep).

With regular bitcoins, I see that when I configure gear to wait for 6 confirmations and 24h, Gear sends two notifications. One for event #2 (transaction included in block) and one for event #3 (transaction confirmed).
With testnet, when configured the same way it behaves the same way, only the testnet blocks are tiny and sometimes happen frequently. But when configured to not wait for confirmation (and only wait for 15 minutes), Gear sends a single notification, after event #1 (transaction transmitted).
What I actually want is to be notified as soon as possible after the customer has transmitted a transaction (event #1), and be notified within minutes of the transaction being fully confirmed (event #3).
If no transaction was transmitted within the first 15 minutes, consider the order abandoned (and the payment address eligible for reuse).
I think what I want is reasonable. But I don't see how to get it from Gear.
Is there a way to get this from Mycelium Gear? If not, is there an alternative service that does the same thing Gear does, but can send the two notifications I need (event #1 and event #3)?
Alternatively, how do other people do it, without using coinbase/braintree/bitpay and without running a full node client on the server?
My best idea currently is to configure Gear to not wait for confirmation to get the first notification, and then follow up the transaction manually using some blockchain explorer API to find out whether it got included in a block and how many blocks deep, until it's fully confirmed and then I can generate the second notification. But if I have to use a second service (some kind of blockchain exploration API), Gear will be a disappointment.

Mycelium Gear fixed the issue (almost two weeks after I reported it) and now they send a webhook for 0 and for 6 confirmations, exactly the way I want it and the way I think everyone wants it.
I've implemented, tested and never deployed a workaround that uses three different block chain exploring APIs to manually confirm transactions.

As I understand, you need callbacks for 0,1,2+ confirmation. AFAIK, there are two options. Both work in similar ways and you can use your own HD wallet to receive similar to mycelium gear

Blockchain.info Receive API
Blockonomics payment API

Note that if you are running an online store, you still need to use websocket API on browser in addition to the callbacks. This is to let the browser know that the payment is done, and then redirect to server to confirm the payment (without doing busy polling).

If you would like to monitor a btc address and receive a webhook notification when that address sends or receives funds, you can use this Wallet Watch tool.  In addition to webhook, a number of other methods are supported as well (SMS, Email, Telegram, etc).
Disclaimer: I am affiliated with a co-founder of this service.

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


text:
How to do "sendmany" without accounts?
As the account system is deprecated, I am not using it. But when I try use json-rpc call sendmany, I get the error:
"Account has insufficient funds (code -6)"

But when I call getbalance I have more than enough funds

It is possible to use without an account.
Just use "" as from-account.
Example:
sendmany "" '{"mzjqvrPTipexdXzJbCjZExs8keg7nMf4M3":0.01,"mqQ69fPZEeJomEzG85FHfrKQ66x3w6oXwp":0.02}'

Watch out: It will tell you Account has insufficient funds (code -6) when you not have enough funds even if you don't use accounts.
Help:
sendmany "fromaccount" {"address":amount,...} ( minconf "comment" ["address",...] )

Send multiple times. Amounts are double-precision floating point numbers.

Arguments:
1. "fromaccount"         (string, required) DEPRECATED. The account to send the funds from. Should be "" for the default account
2. "amounts"             (string, required) A json object with addresses and amounts
    {
      "address":amount   (numeric or string) The bitcoin address is the key, the numeric amount (can be string) in BTC is the value
      ,...
    }
3. minconf                 (numeric, optional, default=1) Only use the balance confirmed at least this many times.
4. "comment"             (string, optional) A comment
5. subtractfeefrom         (array, optional) A json array with addresses.
                           The fee will be equally deducted from the amount of each selected address.
                           Those recipients will receive less bitcoins than you enter in their corresponding amount field.
                           If no addresses are specified here, the sender pays the fee.
    [
      "address"          (string) Subtract fee from this address
      ,...
    ]

Result:
"txid"                   (string) The transaction id for the send. Only 1 transaction is created regardless of
                                    the number of addresses.

Examples:

Send two amounts to two different addresses:
> bitcoin-cli sendmany "" "{\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\":0.01,\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\":0.02}"

Send two amounts to two different addresses setting the confirmation and comment:
> bitcoin-cli sendmany "" "{\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\":0.01,\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\":0.02}" 6 "testing"

Send two amounts to two different addresses, subtract fee from amount:
> bitcoin-cli sendmany "" "{\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\":0.01,\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\":0.02}" 1 "" "[\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\",\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\"]"

As a json rpc call
> curl --user myusername --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "sendmany", "params": ["", "{\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\":0.01,\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\":0.02}", 6, "testing"] }' -H 'content-type: text/plain;' http://127.0.0.1:8332/
 (code -1)

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


text:
What wallets are affected by the NPM package vulnerability?
Recently, a vulnerability was found in an open-source project used by some bitcoin wallet software (such as CoPay and BitPay).
Are there any other wallets known to be affected by this vulnerability?
If I am a user of this software, what steps can I take to secure my bitcoin?

Only Copay is affected by this vulnerability.
Although the package was included by many, many projects (both within and outside the crypto space), the attack payload was encrypted, and used the package description as a decryption key. They key in question was found to be (via brute force) A Secure Bitcoin Wallet, which is the npm description for the copay-dash package.
Thus, packages which did not have that as their description would be unable to decrypt, and hence execute, the payload.
Note that such attacks are feasible on any package that does not verify and pin its dependencies, even outside the nodejs ecosystem. Developers should work to ensure that they are importing vetted code, and pin (or even vendor) their dependencies. This is especially important for programs that deal with private keys.

Can you define the verb "vendor"?  I could only find the noun in major dictionaries.

@Kevin Vendoring means to keep a copy of a specific version of an external code dependency within your repository, so that you are always sure of what code you are running. It also prevents a third party from changing code without changing the version number and slipping it into your application.

Ah.  We do that all the time.  It also makes it easier to fork the dependency and/or submit pull requests (which can be a double-edged sword if you don't have enough people or expertise to support a fork, but at least it gives you options).

I picked vendoring based on what we call it in golang, I'm not 100% certain if the js folks have a specific term for it.


text:
Estimate smart fee returns an error
I am trying to get current fee for per transaction. So running command
bitcoin-cli estimatesmartfee 6

i am getting response lookl ike this
{
  "errors": [
    "Insufficient data or no feerate found"
  ],
  "blocks": 1
}

How ca I get real fee?
Thanks!

Is the node fully synced?

what do you mean saying fully synced? maybe no

Has it downloaded and verified all of the blocks? You can check with $ bitcoin-cli getblockcount

I got response - 1315692

looks like you're on testnet, there are 1414793 blocks so almost synced... https://live.blockcypher.com/btc-testnet/

yes I have on testnet!  its full node ? and why i cant to get fee ?

It appears the node is not fully synced the entire blockchain. If your node is not fully synced, then it hasn't parsed the latest blocks to see what a reasonable tx fee would be for the current market. If it's not fully synced, then it might try to estimate based on old transactions, which you don't want, since they could be much lower (and your tx will never confirm), or much higher (and you overpay in fees).

how can I sync ?

I assume it is syncing, is the number increasing when you check $ bitcoin-cli getblockcount? It takes a while to download and verify all of the blocks, sometimes days or weeks depending on your machine specs.

I just run this command and got response new number. but the command estimatesmartfee not working yet!

cool sounds like it's syncing, just need to be patient.


text:
Generating private key/bitcoin address based on a "password"
Since the private key is basically a random large number, would I be able to pick a password and have that converted into an address?
For example: pick "mysecretpwd". Have it sha256ed, obtain a large integer that is the private key from which I can easily derive the public key and the bitcoin address.
Then for spending any funds received at that address I only need to remember "mysecretpwd", no private key storage on paper, mnemonics or anything, basically the funds are stored in my brain.
What are the security/privacy implications?

What you are describing has been done before, and is known as a "brain wallet".
In earlier days, some wallets and online website did use this system. However, it has proven quite insecure, as humans are terrible at picking secure random data for the "password", and computers are great at guessing them. Many BTC have been stolen from insecure brainwallets, and at this point we have much better and safer means of easily accessing wallets, namely BIP39 seeds.

So you're saying that it is feasible for a computer to brute-force a strong 20 characters alphanumerical/symbol password that I sha256 a million rounds?

@TedyS. yes. see here

I think what the folks at bitcointalk were advising against is using a simple dictionary word that is susceptible to rainbow table-like attacks. I would imagine an attacker's chances drop substantially if the hashing is done multiple times, like I said earlier maybe a million.

https://en.bitcoin.it/wiki/Brainwallet

@TedyS. to be fair to Raghav, your original question did not mention a million rounds of hashing (so implicitly one only) and your example passphrase is composed only of simple dictionary words and commonplace abbreviations in all lower-case ASCII letters. Answerers can only answer the question you actually post, they can't anticipate how you might subsequently move the goalposts.

@RedGrittyBrick that is indeed correct. And I assume one cannot simply standardise an algorithm for generating the private key from the "password" because then it would be well known for attackers as well, right? But that still does not mean I cannot generate an extremely secure one (against bruteforcing) with a custom algorithm involving multiple hashing, right?

@TedyS. In security critical code it is virtually always considered incredibly foolhardy to go against long-established and long-proven experience such as that given in the link in JBaczuk's comment and, for example, here or here. You might be right but I am not going to endorse an approach that seems long discredited. I know my limits (or think I do) - Sorry.

@TedyS re "one cannot simply standardise an algorithm for generating the private key from the 'password'" - See https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki. A broadly accepted principle in the field of information-security is that using well-known or standardised algorithms is usually the safest, even if your enemies know which algorithm you use.

@TedyS. Adding a million rounds of hashing does not actually add much entropy, and is trivial for an attacker to compute. Please heed the warnings of others here, and use well-established cryptographic techniques for generating a private key. Brainwallets are very well known as being insecure.


text:
How is bitcoind "shy" when exchanging `version` packets?
This is more of a technical/programming question.
I am referring to this line of code: https://github.com/bitcoin/bitcoin/blob/be992701b018f256db6d64786624be4cb60d8975/src/net_processing.cpp#L1699
I understand the logic behind not sending a version packet to a newly accepted connection unless they send one first, but the code I linked to does not quite do that, or does it?
At that point we are already inside an if block which verifies that the command received is "version", so the peer has already sent us a version packet, irrespective of who initiated the connection. Am I missing something?

First the peer who chooses to connect shares their version.
Each of the peers can only send one version message.

PushNodeVersion is used to send the version message. It is called by two functions
1) PeerLogicValidation::InitializeNode when the connection is outbound.
2) ProcessMessage when a message is received. It looks like this:
bool static ProcessMessage(...) {
    if (strCommand == NetMsgType::VERSION) {
        if (pfrom->fInbound)
            PushNodeVersion(pfrom, connman, GetAdjustedTime());
    }
}

If it was
    if (strCommand == NetMsgType::VERSION) {
        // If this if clause didn't exist: if (pfrom->fInbound)
            PushNodeVersion(pfrom, connman, GetAdjustedTime());
    }

Consider the following case:
1) Client A connects to Client B
2) Client A sends its version to Client B
3) Client B, as an answer, shares its version
Now, if that if caluse didn't exist, Client A would send the version message once again.
The comment // Be shy and don't send version until we hear is actually irrelevant.


text:
Install chrom on Asic
I want to use antminer-s9 to mining from cryptotab site
This site is much more than any pool give bitcoin
Bot it doesn't have any pool . And just must use Chrome to mine
Any one know how can I install chorom on Asic or a way to connect my antminer to this site?

Cryptotab must surely be a scam, or at least something different than you think.  There is no way that a browser running on an ordinary computer can mine even a penny's worth of Bitcoin.

One possibility is that Cryptotab mines currencies other than Bitcoin, that use some hash algorithm other than SHA256D that can be done efficiently on a CPU.  But your AntMiner inherently can only do SHA256D, so it is not possible to use it to mine currencies that use other algorithms.

You might be able to run chrome on an ASIC. But if you did, whatever it mines in a tab would not make use of the ASIC hardware.
Firstly, an ASIC is not a general purpose computer, it cannot just run whatever software you want on it. It does have a small general purpose computer for managing the ASIC hardware, but that is a low powered computer. This low powered computer has a CPU which you could compile a version of Chrome for and copy the binaries to it. Then you could start an X server to get a GUI over the network and view it on another computer.
However, this would not be useful to you at all. Chrome would not be able to use the ASIC hardware. It can only use the general purpose CPU, which, in this case, is super low powered. It would not mine any more coins than a regular computer, in fact, it will most definitely mine much much less, if any at all.


text:
How can I check where my bitcoins have gone to in my app?
 help
I need to know where to go search my bitcoins after they entered my account on my bitcoin app...so far its two day still nothing showing....

It's unclear what you're asking, what software you are using.

When did you send it? I mean how long has it been since you sent the bits?

If its been a reasonable time(e.g. 6+ hours), please let me know if you have access to the sender/receiving address? Then you can track your transaction via some blockchain explorer like this one.

That looks like the unimaginatively named "bitcoin wallet"
I would review the transaction details provided by the sender of the Bitcoins. If you have a transaction-id or receiving-address you can look it up on a blockchain explorer to see what is happening.
A few obvious possibilities to bear in mind

insufficient mining fee
incorrect recipient address
problems with wallet configuration

not syncing with bitcoin network
private key not imported?


text:
Paying to one address using inputs from multiple addresses under same seed
I am using bitcoin core and I was wondering. If I make a bitcoin payment using bitcoin-cli which has about 50 addresses registered to it. If the payment is for 1 BTC and I pay from the address A1 (let's use A1 instead of an actual address) but A1 doesn't have enough balance will it take money from other wallets automatically to help pay the set amount? If not then how can I make it so?
Edit: I am using 'getnewaddress' when generating these other addresses.

AFAIK bitcoin-cli doesn't have a way to send a payment "from" a particular address, other than manually using raw transactions. There is a sendfrom command that will send from a particular account, which may encompass many addresses, but the whole feature of accounts is deprecated and shouldn't be used at all.


text:
USDT transfer at BTC address from binance exchange
I am transfer USDT to BTC address by mistake but since last 3 month USDT missing .how I will take back in my account.
  Binance not help me for get back my USDT.or BTC. They r saying when your transection abnormal or cancel you contact us.since last 3 month I am reading these by binance.

The btc address you transferred the coins to, does it belong to you or binance? If it is yours, then you can be able to recover it without needing binance.


text:
Ethereum's PoW difficulty
Bitcoin's block time is about 10 minutes while that of Ethereum is 15 secs. Both are using PoW at this moment, right? How come Ethereum's block time is so short compared to Bitcoin? Is hashing a lot easier?

Because it was designed to be that way. Ethereum targets 15 seconds, so the difficulty adjusts to make the block interval 15 seconds. Bitcoin targets 10 minutes, so the difficulty adjusts to make the block interval 10 minutes. It is unrelated to how difficult it is to produce a hash; it is only related to what hashes are considered valid.
The set of hashes considered valid is set by the difficulty adjustment. Making it smaller means that it will be take longer or require more hash rate to find a valid block hash. Making it larger has the reverse effect. So Ethereum has a larger set of valid hashes than Bitcoin, so valid block hashes can be found more quickly as fewer hashes need to be tried, on average.


text:
How is a node selected to run Smart Contract in Ethereum
A node that runs a smart contract will be paid with GAS. How is this node selected? I guess this node should be trustworthy. Or multiple nodes are running the same smart contract just to make sure somehow?

A node that runs a smart contract will be paid with GAS.

This is incorrect. The miner who mines the block containing the transaction interacting with a contract is the one who is paid with ETH, which is gas consumed * gas price.

How is this node selected?

Through the mining process.

Or multiple nodes are running the same smart contract just to make sure somehow?

Even after the block is mined, every node on the network that receives it will independently validate the contract execution. If the miner lies about the outcome of the execution, the block will be deemed invalid.


text:
How are difficulty level and block reward determined and stored in decentralized fashion in Bitcoin?
I know the difficulty level and block reward are periodically adjusted in Bitcoin to keep the block time approximately to 10 minutes.
I guess these are not determined by a central authority but rather are determined in decentralized fashion. If so, what are the exact steps involved here? Each node independently computes on their own, propagates and will it be verified?

This seems like pretty well defined topics in Bitcoin, is there specific question or thing you don't under stand? Instead of of trying to explain the most general things which are probably already explained elsewhere in more appropriate format. Also simply describing exactly how the protocol works would be lengthy. Like block reward is the first transaction on a block, but you can go much exact than that.

You are right @PieterWuille. The question has this answer which I was looking for: "... but really each separate node calculating and enforcing it independently ..."

Each node independently computes it on its own, following the formula:
At every block n with n beingg a multiple of 2016, look at the time stamps of the past 2015 blocks, and change the difficulty for what follows to old_difficulty*(2 weeks)/(time the past 2015 blocks took)
Each node does that calculation to make sure that any new block it finds will have sufficient difficulty in order to get accepted by other nodes on that network. This is all about how Bitcoin is kind of self-organized. A node can find a block with too little difficulty, but that will be next to useless as this block won't get accepted into the chain.


text:
How can I sign message for a blockchain watch only bitcoin address
I have to verify sign message for one of my blockchain bitcoin address. I couldn't find sign message or private key option in More Options beside all my bitcoin addresses. I thought maybe I have to import it.So I imported my own blockchain bitcoin address which I am mentioning below
1PSBpnjrzpHyKpyQuFaecdnA4WfDetdiwn
and it became a watch only address. In More Options I see only Archive, transfer and spent.
So what to do now ? Please help...
I do not have any bitcoins on this address, but I logged in using this bitcoin address as master address on a bitcoin gambling site and forgot the password.The only way I can recover my account is by verifying my bitcoin address
1PSBpnjrzpHyKpyQuFaecdnA4WfDetdiwn and pasting the signature to be provided by blockchain. I don't want to lose my BTC and LTC on this account.
So what to do now ? Please help...

When you import an address as a 'watch only' address, it means exactly that: you can only 'watch' the address and see whatever funds are sitting in it. You cannot send transactions, or sign messages, with a watch only address.
This is because you just imported the address into your wallet, whereas if you imported the private key, then you would be able to sign the message (and send transactions, etc).
So you'll need to find some wallet software that can sign messages (and that you trust). Import the private key for that address, and then sign the message.

Thankyou so much. Can you suggest some bitcoin wallet software that will provide me with private key for my watch only address or sign message for my watch only address

@57bits If you don't have the private key, the address is not yours, and there is nothing we or you or anyone can do about it. As the name says, you are only watching the address. You must have imported it somewhere without access to the corresponding key. If you don't already have the key, that's the end of the story.

@57bits If you use the wallet that generated this address then the private keys should be there.

You can not sign a message with watch only address.
Signing requires private key.


text:
lightning network funding transaction clearification
Im trying to understand the funding transaction for a channel on the lightning network. I am wondering how the input looks like to the funding transaction. Does it require In_{Alice}(tx_{id}, tx_{index},redeem_script) and In_{Bob}(tx_{id}, tx_{index}, redeem_script) as inputs to the transaction or do you just see the first commitment transactions (like Ca1, C1b) from the multisig and and ensure they are valid then asynchronously submit funds to the multisig address? [0] just shows the output format as the multisig.
[0] https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md

the input of the funding tx is just an input that is able to spend some UTXO which either Bob or alice controlled. Theoretically we could have Inputs from Bob and Alice but I believe that is not being implemented yet.
The workflow goes as follows. For example alice decides to open a channel by creating a funding tx. The output of the funding tx is a 2-2 multisig P2SH so before broadcasting the funding tx there will be 2 commitment tx created. one for alice and one for bob (in order to be able to ascribe blame in case auf malicious behavior) only if the commitmet tx are successfully signed the funding tx will be broadcasted to the bitcoin network and only if it has enough confirmations the channel will become operational.

The input(s) of the Funding Transaction are not specified as there is no need to do that. This is because only one party can fund the channel (the one that sends an „open_channel“ message to another LN node).
For example:
Lets assume Alice wants to create a channel with Bob. In this case, Alice is the only funder of the channel. So she creates a Funding Transaction with one or more inputs (that reference her UTXOs) which sum up to a total of 1 BTC. She also creates the first Commitment Transaction which refunds her 1 BTC (she can broadcast this transaction in case Bob won't cooperate anymore). That means, the second Commitment Transaction is actually the first transaction that Alice can use to pay Bob. Note that Bob cannot pay anything to Alice with the second Commitment Transaction as only Alice funded the channel and hasn't paid Bob anything yet. Now what if Bob wants e.g. to pay 1.5 BTC to Alice? Well, he can simply (try to) open another channel with Alice by sending her an „open_channel“ message. If Alice accepts the request, Bob funds the channel with 1.5 BTC and can then send money to Alice.


text:
Why is a softfork unable to divide the network?
I was wondering why a soft fork cannot in principle divide the Bitcoin network as a hard fork can.  I understand that a soft fork, by definition, involves only tightening the consensus rules, but the result will still be two different sets of consensus rules.  If some nodes consider a block or transaction valid and others consider it invalid, a network divide should be possible regardless of which side's consensus rules are newer.  The roles of each side in the division would simply be the reverse of the hard fork case.

I was wondering why a soft fork cannot in principle divide the Bitcoin network as a hard fork can.

A soft fork absolutely can divide the Bitcoin network, in principle, if you don't specify any other assumptions.
However, the relevant point that distinguishes soft and hard forks is that the network will always converge as long as a majority of the hashrate enforces the new rules.
The reason for this is that even when old miners would produce a block that violates the soft fork's rules, the new miners will not work on top of it. They will ignore such a block, and start working on a competing branch instead. As they have the majority, this competing branch will at some point overtake the old miners' branch. The backward compatibility of the softfork means that old miners at that point will switch over to the new branch, abandoning their own, as the new branch is longer and is valid to them. Through this, the fork is resolved, and the whole network ends up working on one chain again.
As you can see above, the remaining old miners will cause increased (temporary) forks in the chain. In order to avoid having these interfere with the security properties of the network, recent soft forks in Bitcoin have employed thresholds of 95% (measured in one way or another) of miner signalling - leaving at most 5% that may produce forks.

Soft forks cannot divide the network because they occur with miner consensus. For this to happen, miners signal that they are ready and will enforce the new rules after they activate by setting certain bits in their block version numbers. Once enough blocks signal readiness (with BIP 9, this is typically 1916 out of a 2016 block retarget period, so 95% of blocks), the new rules will activate.
A chain split does not occur because, in theory, no or few miners are running old nodes in order to produce invalid blocks. Those that are typically upgrade quickly anyways.
Hard forks can do a similar thing to prevent chain splits, however what hard forks are unable to do is to prevent old nodes (non-mining) from being forked off of the network. The backwards compatibility of soft forks allows old nodes to remain on the network following the activation of the fork.

Under a hard fork, new nodes think old-style blocks are invalid, and old nodes think new-style blocks are invalid.  Thus if old nodes continue creating old blocks, we get a chain of old blocks, and a chain of new blocks.  Each community thinks theirs is the one true blockchain.
Under a soft fork, new nodes think old-style blocks are invalid, but old nodes think both types of blocks are valid.  New miners, which we assume are in the majority, will create a chain of new blocks only.  Old miners may try to create old blocks within this chain, but since new miners won't accept those blocks, they'll get orphaned.  The old nodes will think the old miners are just unlucky, and they'll continue to accept the longest chain of blocks which they consider valid.  In the long run, since new miners are in the majority, this longest chain will in fact consist only of new blocks.
So in a soft fork, the old nodes will agree that the chain of new blocks is the one true blockchain, without having to be upgraded, simply by virtue of the fact that it will become longer than any chain containing old blocks.


text:
With the btc price changing every second, how can you accurately display conversion to fiat currency?
So the ASK price of BTC is constantly moving -- every second. I'm trying to build out a simple UI where the user can enter in the amount of BTC they want to buy, and then display how much that will cost them in USD. But when the user finally presses the 'Buy' button, the price of BTC might have changed slightly, and the user will be charged a different value of USD than what was displayed in checkout. WTF? Is there a way around this? How are other exchanges handling this? I know this can be achieved with limit orders and such, but I'm trying to accomplish this with simple market orders.

There is not a way around this unless you are using an exchange. But, even exchanges have a disclaimer:

Market orders may be partially filled at several prices. Each part of
  your order will be shown in the fills panel. See Coinbase Pro - overview of order types

The way exchanges work is sellers place limit orders, which show up on the order book. When a buyer does a market order, it will buy up the lowest priced volume that is already on the order book. Basically, you have to remember there is a seller for every buyer, and everyone is choosing their price. Things happen fast, if your order is placed right after someone else buys all the volume at the price you wanted, you might get a different price.
Your best option is probably to use an exchange api, and get a feed of the order book, so it is as real-time as possible. E.g. see Coinbase Pro API and their Level 2 channel in Websocket Feed.


text:
Extended Public Key 's mechanism misinterpreting in 'Mastering Bitcoin' by Andreas
I am a newbie and start exploring from the 'Mastering Bitcoin' book. The figure below to me is a little inaccurate, I think the arrow from HMAC-SHA256 should point right to the child public key. Am I right??

I think the arrow from HMAC-SHA256 should point right to the child
  public key. Am I right??

No, there are 3 derivation functions defined in BIP32 - Hierarchical Deterministic Wallets

Private parent key → private child key
Public parent key → public child key
Private parent key → public child key

The diagram above illustrates
1. Private parent key → private child key
Perhaps you're confusing this for 2. Public parent key → public child key. Another potential confusion is that this is not for a hardened child key but a normal child key, which uses the parent public key point(kpar), combined with the parent chain code cpar and the index i. These are combined and hashed to I as follows:
I = HMAC-SHA512(Key = cpar, Data = serP(point(kpar)) || ser32(i))
I is split as shown in the diagram, where the left 256 bits IL are combined with the parent private key kpar to produce the child private key ki:
ki = parse256(IL) + kpar (mod n)
IR is the new child's chain code at that index i, and the child public key is then calculated like normal using elliptic curve secp256k1 from the child private key itself.

so if this figure is meant to to demonstrate how to “Extending a parent public key to create a child public key” it would be wrong, right? sorry I didn't post with the note included

It would be wrong in that case

I have to agree, https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch05.asciidoc still needs a little work.
Here is my perspective, the application of BIP32 Deterministic Key Generator and bitcoin explorer (bx) can be applied to obtain a data flow picture for what is really going on with extended keys. This requires and understanding of the constituent fields of extended keys and understanding those fields provide inputs for operations that are frequently cascaded in practice, e.g. implementing the BIP 44 Standard using HD wallets.
Each extended key, xprv or xpub, has the following six fields: 1) Version, 2) Depth, 3) Parent Fingerprint, 4) Child Index, 5) Chain Code, 6) Key.  The key is either the private or public elliptic curve key depending upon if the extended key starts with xprv or xpub for bitcoin.  Note that bx extends the entropy to 12, 15, 18, 21, or 24 triplets of BIP 39 words as a function of the the number of hexadecimal digits cut, using the UNIX cut command. Here is how 12, 18, and 24 BIP 39 seed words are synthesized using bx.
% echo "brain wallets typically have poor entropy" | bx base16-encode | bx sha256
f09538a516514dc74510b08e9d61a0f0200097b4304a88dd96ef613ec3c6f3b3
Now plug the hexadecimal number immediately above into the BIP32 JavaScript program's Input Your own Entropy field, click the Base 16  (0-9,A-F) (For 16-sided dice) radio button, and finally click the Generate New Phrase button. Contrast to the results generated by bx.
% echo "brain wallets typically have poor entropy" | bx base16-encode | bx sha256 | cut -c 1-64 | bx mnemonic-new
vacuum prefer citizen coach below together begin bid model twelve habit theory abandon envelope speak announce match uncover rookie second umbrella toddler solution legal
% echo "brain wallets typically have poor entropy" | bx base16-encode | bx sha256 | cut -c 1-48 | bx mnemonic-new
vacuum prefer citizen coach below together begin bid model twelve habit theory abandon envelope speak announce match tribe
% echo "brain wallets typically have poor entropy" | bx base16-encode | bx sha256 | cut -c 1-32 | bx mnemonic-new
vacuum prefer citizen coach below together begin bid model twelve habit tiger
Notice all the word group sets match to the maximum extent possible except the last word. This is because with BIP 39, the last word of a 12 word sequence has a 4-bit checksum built into it, the last word of a 18 word sequence has a 6-bit checksum built in, and the last word of a 24 word sequence has an 8-bit checksum built in. You can think of the BIP 39 enabling base 2048 encoding with the last word providing checksum information in accordance with the table here.
Now enter the PassPhrase "Hello its me 123!" (typically of your choosing) into the Optional password field and press the enter key.  Contrast the results to:
% echo "vacuum prefer citizen coach below together begin bid model twelve habit theory abandon envelope speak announce match uncover rookie second umbrella toddler solution legal" | bx mnemonic-to-seed -p "Hello its me 123!" | bx hd-new -v 76066276
xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby
Now contrast these six piped bx command line sequences to the six fields created by the BIP 32 JavaScript.
1) Version:
% echo xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby | bx base58-decode | cut -c 1-8
0488ade4  (where 0x0488ade4 = 76066276 base10)
2) Depth:
% echo xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby | bx base58-decode | cut -c 9-10
00
3) Parent Fingerprint:
% echo echo xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby | bx base58-decode | cut -c 11-18
00000000
4) Child Index:
% echo xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby | bx base58-decode | cut -c 19-26
00000000
5) Chain Code:
% echo xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby | bx base58-decode | cut -c 27-90
ecdd0dc94d9686e0c5925f0c5657945c370daa9218afae35a75d63ecc9d5c719
6) Private secp256k1 Elliptic Curve Key:
% echo xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby |  bx base58-decode | cut -c 93-156
ee3c1e5f21505c8d1f8ad137fc5a7021f1be309ab1c3cb2bf7e9df80e6521b6f
or
% echo xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby | bx hd-to-ec
ee3c1e5f21505c8d1f8ad137fc5a7021f1be309ab1c3cb2bf7e9df80e6521b6f
Now for the freekin cascading HMAC-SHA512 mathematical magic for calculating up to 2 to 4 billion public keys and associated public addresses for extended public keys. Note that the following two piped calculations produce identical answers except the means for calculating the results vary, examine carefully. From a business process re-engineering perspective, this is a cryptographic death knell for expensive credit card PCI-DSS customer protection compliance for existing web commerce servers requiring sensitive personal credit card information. Commerce servers accepting crypto don't need to have private keys exposed to process each customers shopping cart's payments.
% echo xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby | bx hd-private -d -i 44 | bx hd-private -d -i 0 | bx hd-private -d -i 3 | bx hd-private -i 2 | bx hd-public -i 1
xpub6HCiK4CPBLGVw2fJ9bpjHRQ9JwMK2GpcHjszHsvSYZQ6xezqdbiwa2U3QGgKqRdfFNCma9XxXRpaTU2tW9KkgKv6BafobcZmCys5GpZN5QG
or
% echo xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby | bx hd-private -d -i 44 | bx hd-private -d -i 0 | bx hd-public -d -i 3 | bx hd-public -i 2 | bx hd-public -i 1
xpub6HCiK4CPBLGVw2fJ9bpjHRQ9JwMK2GpcHjszHsvSYZQ6xezqdbiwa2U3QGgKqRdfFNCma9XxXRpaTU2tW9KkgKv6BafobcZmCys5GpZN5QG
Now plug the xpub* extended key immediately above into the BIP32 Extended Key field and press enter and contrast the results to the info below:
1) Version:
% echo xpub6HCiK4CPBLGVw2fJ9bpjHRQ9JwMK2GpcHjszHsvSYZQ6xezqdbiwa2U3QGgKqRdfFNCma9XxXRpaTU2tW9KkgKv6BafobcZmCys5GpZN5QG | bx base58-decode | cut -c 1-8
0488b21e    (where 0x0488ade4 = 76066276 base10)
2) Depth:
% echo xpub6HCiK4CPBLGVw2fJ9bpjHRQ9JwMK2GpcHjszHsvSYZQ6xezqdbiwa2U3QGgKqRdfFNCma9XxXRpaTU2tW9KkgKv6BafobcZmCys5GpZN5QG | bx base58-decode | cut -c 9-10
05
3) Parent Fingerprint:
% echo echo xpub6HCiK4CPBLGVw2fJ9bpjHRQ9JwMK2GpcHjszHsvSYZQ6xezqdbiwa2U3QGgKqRdfFNCma9XxXRpaTU2tW9KkgKv6BafobcZmCys5GpZN5QG | bx base58-decode | cut -c 11-18
f32fe933
4) Child Index:
% echo xpub6HCiK4CPBLGVw2fJ9bpjHRQ9JwMK2GpcHjszHsvSYZQ6xezqdbiwa2U3QGgKqRdfFNCma9XxXRpaTU2tW9KkgKv6BafobcZmCys5GpZN5QG | bx base58-decode | cut -c 19-26
00000001
5) Chain Code:
% echo xpub6HCiK4CPBLGVw2fJ9bpjHRQ9JwMK2GpcHjszHsvSYZQ6xezqdbiwa2U3QGgKqRdfFNCma9XxXRpaTU2tW9KkgKv6BafobcZmCys5GpZN5QG | bx base58-decode | cut -c 27-90
fcab24d09be9a54f466c633f24cf76927b90ed2235513d00bc76582e21fdde10
6) Public secp256k1 Elliptic Curve Key:
% echo xpub6HCiK4CPBLGVw2fJ9bpjHRQ9JwMK2GpcHjszHsvSYZQ6xezqdbiwa2U3QGgKqRdfFNCma9XxXRpaTU2tW9KkgKv6BafobcZmCys5GpZN5QG | bx base58-decode | cut -c 91-156
03f800bc151043e197697bf44d90ffa2f9fee3bccc3b49f36f29cee527f3f9af75
or
% echo xpub6HCiK4CPBLGVw2fJ9bpjHRQ9JwMK2GpcHjszHsvSYZQ6xezqdbiwa2U3QGgKqRdfFNCma9XxXRpaTU2tW9KkgKv6BafobcZmCys5GpZN5QG | bx hd-to-ec
03f800bc151043e197697bf44d90ffa2f9fee3bccc3b49f36f29cee527f3f9af75
Calculation of associated M/44'/0'/3'/2/1 compressed public address:
% echo xpub6HCiK4CPBLGVw2fJ9bpjHRQ9JwMK2GpcHjszHsvSYZQ6xezqdbiwa2U3QGgKqRdfFNCma9XxXRpaTU2tW9KkgKv6BafobcZmCys5GpZN5QG | bx hd-to-ec | bx ec-to-address -v 0
1HaigDWQCAu3eJQnKivhVifcrcQDEYdDBH
Calculation of associated m/44'/0'/3'/2/1 compressed WIF key:
% echo xprv9s21ZrQH143K4R8iufF8sxh3Y5S14mhwn5qLFdi1gymFpr7DWKmMwttkAsLMDYpgJBfNmzTnFUKiveLKZBWzad4A43whiGzWhLtbbwdBQby | bx hd-private -d -i 44 | bx hd-private -d -i 0 | bx hd-private -d -i 3 | bx hd-private -i 2 | bx hd-private -i 1 | bx hd-to-ec | sed 's/$/01/' | bx base58check-encode -v 128
KzNMg2qRVNBbr2QnAzc2bYvf7cM2t4GQ2LiL1Q5VYgWipTrrPKbX

thank you for such a thorough answer and demonstration, I wish you good health


text:
Bitcore explorer insight testnet initialisation
I am using bitcore explorer and I want to initialize insight api in testnet.
It has the following code.
I try var insight = new Insight('testnet') but it is not working.
What value for url should i input so that  Networks.get(url) === testnet
function Insight(url, network) {
  if (!url && !network) {
    return new Insight(Networks.defaultNetwork);
  }
  if (Networks.get(url)) {
    network = Networks.get(url);
    if (network === Networks.livenet) {
      url = 'https://insight.bitpay.com';
    } else {
      url = 'https://test-insight.bitpay.com';
    }
  }
  JSUtil.defineImmutable(this, {
    url: url,
    network: Networks.get(network) || Networks.defaultNetwork
  });
  this.request = request;
  return this;
}

Try this
const bitcore = require("bitcore-lib");
const Insight = require("bitcore-explorers").Insight;
insight = new Insight(bitcore.Networks.testnet);

then do the rest.


text:
Verify bitcoin address and amount from sign transaction
Is there a way i can extract the fromAddress, toAddress, amount and fees from a bitcoin sign transaction?
eg: SignTransactionValue = signAddress(fromAddress, toAddress, amount, fees, privateKey)
How can i extract back fromAddress, toAddress, amount and fees from the signTransactionValue?

What does signAddress produce? What do you mean by SignTransactionValue? This is not standard terminology and could mean many different things.


text:
extract wallet address from private key
I am using bitcoin core library in node js.
const privateKey = new bitcore.PrivateKey('testnet');
const address = privateKey.toAddress('testnet);

When i console.log it, it get result as below. How can i extract the address part only? I try to use address.Address but it returns undefined
<Address: mmNeqV9HWKUDRUAVdknRKDPHyKYGpBEDzm, type: pubkeyhash, network: testnet>

it's better to get public key first then convert it to address
var publicKey = privateKey.toPublicKey();
var address = publicKey.toAddress(Networks.livenet);

address is an object, you can use it as a string. if you want to see it in console try
console.log("Address: ", address);

why is it better to get public key first before convert it to address? I found that it returns the same result also even without convert to public key first. any  technical explanation on that?

Because you're creating the address from the public key not from the private key. so technically for better understanding when you call privateKey.toAddress bitcore by default get the publicKey and then the address.

please see this answer here: https://bitcoin.stackexchange.com/questions/75910/how-to-generate-a-native-segwit-address-and-p2sh-segwit-address-from-a-standard

You should have the public key first to get bitcoin address.
var publicKey = privateKey.toPublicKey();
var address = publicKey.toAddress(Networks.livenet);

Check out the link to know "How bitcoin address is generated from the public key".
Better to try yourself in this Playground.

Highly confusing.
Just console log it AS A STRING.
This line
console.log("address", "" + address);

will print out
address 1HSfafDJ6ijRxSjj2aTAq2Vb63TAnQK9fz

On the other hand if you just log the address object
console.log("address", address);

You will get
address Address {
  hashBuffer: <Buffer b4 5c 9d e7 ce 0c 89 ee aa 5e 8a 24 b2 5a ff 0b dd f6 9d 42>,
  network: Network {
    name: 'livenet',
    alias: 'mainnet',
    pubkeyhash: 0,
    privatekey: 128,
    scripthash: 5,
    bech32prefix: 'bc',
    xpubkey: 76067358,
    xprivkey: 76066276,
    networkMagic: <Buffer f9 be b4 d9>,
    port: 8333,
    dnsSeeds: [
      'seed.bitcoin.sipa.be',
      'dnsseed.bluematt.me',
      'dnsseed.bitcoin.dashjr.org',
      'seed.bitcoinstats.com',
      'seed.bitnodes.io',
      'bitseed.xf2.org'
    ]
  },
  type: 'pubkeyhash'
}


text:
Why does the order in which the transactions occur matter when we reconstruct ownership information?
I was wondering why the order in which the transactions occur matters when we reconstruct ownership information. Can't we just aggregate all the input and output for each account to calculate how much it owns?

I was wondering why the order in which the transactions occur matters when we reconstruct ownership information. Can't we just aggregate all the input and output for each account to calculate how much it owns?

There are no accounts on Bitcoin, but even if there were accounts, how would you deal with the case where the sum of the transactions exceeds the funds necessary for all of them to be valid?  Transaction order is necessary to deal with that case.  Here's an example:

Mallory receives 1 BTC to her account
Transaction A spends 0.5 BTC to Alice from Mallory's account
Transaction B spends 0.5 BTC to Bob from Mallory's account
Transaction C spends 0.5 BTC to Charlie from Mallory's account

Assuming negative balances are forbidden, the order of these transactions determines who gets paid.
Because transaction order matters, and for other reasons, Bitcoin doesn't have accounts.  Each time you receive funds, it's paid to an output that's uniquely identifiable.  That is, it may have the same spending condition (e.g. address) as other outputs you've received, but each output can be uniquely identified by the transaction it appears in (txid) and its sequence in the series of outputs in that transaction (output index number, or output vector (vout)).
When you spend funds, you create an input that uses that unique identifier (called an outpoint) to references the output you're spending.  Bitcoin only allows you to spend an output once within a block chain (an ordered list of transactions), so you have to spend all of the value of that output or you lose the value you don't spend.


text:
use old offline phone as a hardware wallet?
here's what i want to do:
store my private key on an offline phone.
use that offline phone to generate a signed transaction and generate a QR code for me to scan/broadcast with my online phone.
does this exist?!? i cannot find an app to do it
seems like the most secure/convenient way to use bitcoins.

Beware: phones are built for connectivity. To make a truly offline device you'll want to take extra steps to ensure you remove all connective functions (wifi, bluetooth, etc) from the device. Otherwise this is a reasonable idea, though I'm not sure what software is mobile-ready to display signed transactions in the way you need.

that's a good tip. i thought even if i have 100 virus on my phone it won't matter because it'll never go online. but what if the virus re-enables online o.o
also i need to make sure to encrypt phone's data, just in case it's stolen there's no keys on the drive

electrum android app can do this! check it out, it's perfect!
also seems like a nice wallet with a lot of features.
your watch-only online electrum can create an unsigned transaction with QR code.
your offline electron can scan then sign it & generate a QR code for you to broadcast with online electrum!

i recommend using multisig instead. same idea, just an extra level of security by also requiring the key from your online phone


text:
what if a coin is spendable by multiple keys?
it seems like the scripting language could allow multiple private keys to spend a coin?
what if i send a coin to someone, but also allow it to be spendable by me. would their wallet still show they received the $?

Depends on the wallet. To recognise the transaction at all, their wallet would have to have the script / multisig address in it too. They'd have to have done that themselves, you can't generally trick someone because their wallet simply wouldn't see the transaction at all.

right, obviously depends on the wallet. i was asking about the current popular ones. you're saying they wouldn't recognize it, because it's a weird format? that's good!

Yep! A multisig address starts with a 3 and is indistinguishable from any other address starting with a 3 unless you have the corresponding script

do you need a multisig address to do something like this? you can't lock a coin for 1 of 2 normal bitcoin addresses?

@StephenBugsKamenar That's essentially what a multisig does. You supply m public keys, and say an output can be spent by n of those keys signing the tx (an n of m multisig).


text:
bitcoind starting and then quickly shutting down automatically
Lenovo E460, 8GB RAM,
Fedora 26,
bitcoin core command line version 0.16.0,
All blocks completely downloaded on a flash drive with 256GB capacity.
I rebooted my machine today without stopping the bitcoind before and since then the following happens:
1) starting "bitcoind -daemon -datadir=/path/to/flash/drive"
2) I see with "top" the process 'bitcoind'  running  for about 30-45 seconds
3) Suddenly under same process id the process names changes to "bitcoin-shutdown" and disappears a second after.
4) Stop or new start of bitcoind is not possible, message is "Error: Cannot obtain a lock on data directory /path/to/flash/drive. Bitcoin Core is probably already running."
5) Only way to start bitcoind again is to reboot the linux. Then loop 1)-5) starts again.
Any help appreciated!
Thanks!

can you post the error log?

This is what I see when sarching for the PID in the journalctl:
-- Reboot --
Apr 18 21:40:23 user.fritz.box audit[3373]: ANOM_ABEND auid=1000 uid=1000 gid=1000 ses=3 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 pid=3373 comm="bitcoin-shutoff" exe="/usr/local/bin/bitcoind" sig=6 res=1
Not sure if this is enough. If not in what path are the log/error log files?
Thanks!

Might need to post the whole log, try to use pastebin.com and paste the whole log into it.
Usually under your bitcoin data folder (file named: debug.log)

Thanks! Found it, see here:
https://pastebin.com/embed_iframe/09eG9h9Q

Hmm the log you posted didn't really tell me about why it crashes.
So make sure your usb has 150GB+ storage right?

The USB has 259GB, 190GB used and 70GB free

Can you run it without -daemon and post what happens? Also, to avoid the "Cannot obtain lock error", if you are sure that bitcoind is no longer running (check ps and top), go to the datadir and delete the .lock file.

Without -daemon the response is this:
"Error: Error: A fatal internal error occurred, see debug.log for details
terminate called after throwing an instance of 'std::runtime_error'
what():  CDB: Error 30, can't open database wallet.dat
Aborted (core dumped)
"

ps and top is not showing bitcoind

The new debug file is here:
https://pastebin.com/embed_iframe/eY3kCNQe

the .lock file had 0 Bytes. Didn't delete it. Would need to change the permission. Still helpful where it is empty anyway?

Yes, you have to delete that file.  It's normal for it to be 0 bytes - just the fact that it exists signals to Bitcoin Core that another instance is running.  Of course it would be wise to back up your wallet.dat first, just in case.

Tks! How to delet .locks? rm is not working, reply is "read-only file system". Then I tried to chmod it, same reply. So currenty it's chmod 644 and change of this or deletion vie rm command is not working.

you are giving permissions to file by using chmod, you have to run sudo rm -rf  ...

Thanks! Didn't work yet, this is what I tried:
$ sudo chmod 777 .lock
chmod: changing permissions of '.lock': Read-only file system
$ sudo rm -rf .lock
rm: cannot remove '.lock': Read-only file system

May be uninstalling and new installing helps ... going to try.

Still struggeling: After reinstall it's still not running, but at least I could delete the .locks. with the cmmand line and the GUI version, both give me as feedback "cannot obtain a lock on data directory /path/to/flash/drive/. Bitcoin Core is probably already running"
Further help would be appreciated!

The solution is time consuming but easy. The flash drive was finally reporting read/write errors after a harsh shutdown. Formatting it and new install of bitcoind and loading all blocks again (I had no other drive where I could have copied this amount of data to and wanted to exclude potential issues with the old file permissions).
So the next few days I assume the machine will be busy. However now at block 8000 the CPU is only using 1-2% (Intel Core i5 with 8GB RAM on fedora linux)

Higher dbcache will improve performance. Also, this will destroy your flash drive. Those are not designed for I/O heavy database loads.

Thanks Pieter, I started bitcoind now with dbcache=40000 and maxconnections=40 but still only 2% CPU and 3% memory usage. Any idea?

Yes, don't use a flash drive. It's not designed for heavy database loads.


text:
how to get confirmations about many transaction at once using bitcore node or bitcoind rpc?
how to get the confirmations of many transaction at once using bitcore node or bitcoind rpc?
I think it's possible to get the confirmation of a single transaction using getrawtransaction of bitcoind rpc, but i want to check the confirmations of multiple transaction by one call. Is it possible?
Thanks

Solutions (depending on your use case)

Use JSON 2.0 batch requests (supported in Core)
Use REST with binary export https://github.com/bitcoin/bitcoin/blob/master/doc/REST-interface.md
Use the wallet if your set of scripts you want to watch is known. Use list transactions to get all relevant transactions of a set of keys/scripts

It is not possible in bitcoind RPC without modifying the RPC's code
As to Bitcore, I'm not aware of its RPC usage and features

Based on the developer reference guide https://bitcoin.org/en/developer-reference There doesn't seem to be a direct approach.
However, if you only care about transaction that are below certain number of confirmations, say 6, and deem anything greater than that as confirmed, then I'd simply use listsinceblock with a block header hash that's 6 below the head tip. In this case, you'll either find your transaction in this list with the confirmations field you need, or your transaction has more than 6 confirmations.
Not exactly what you look for, but could work depending on what you really care.


text:
What format is this scriptPubKey?
I'm running BitcoinUnlimited's giga_perf branch of bitcoin in regest mode, and I'm noticing a different format than P2PKH in the scriptPubKey when running listunspent over rpc.
Typically I see scriptPubKey's in the P2PKH format:
'76a914' + b58check_to_hex(address) + '88ac'

But with this implementation I'm seeing:
'2103' + ??? + 'ac'

Some examples below, what format are these scriptPubKey's in?
{
  "txid": "07ad742b0bab1c5e65fe720459747aa687d293fef0d0f168297bcaafbe73f17b",
  "vout": 0,
  "address": "mrjTCJGC7aYdZsy3gUJMpBesgtH1ymybsN",
  "scriptPubKey": "21031f5ce0854d50e632bd7002ae5aff977396376082e45329fcdf1af52ab68f766bac",
  "amount": 50.00000500,
  "confirmations": 101,
  "spendable": true
},
{
  "txid": "d7f623f59d8fa37eea5fafeb3819ecd76750bea9bb48d453e0eb13426c7e707e",
  "vout": 0,
  "address": "n2Faf95smgYu6e9aBVAwwzp6oULnL7SSSs",
  "scriptPubKey": "21039ff795e5433e67b418e100938ac72e2713a1661c15f48a5c198a5086d96285beac",
  "amount": 50.00000000,
  "confirmations": 108,
  "spendable": true
}

Those are Pay to Pubkey scriptPubKeys. P2PK is in the format <pubkey len> <pubkey> OP_CHECKSIG. The 21 is the pubkey length and the 03 is the first byte of the pubkey. The ac is OP_CHECKSIG.

Perfect, can't believe I overlooked that.


text:
What is the safest way to escrow my money before purchasing bitcoins?
While investigating the process of purchasing items with bitcoins, one site that I was learning about suggested, if you don't have bitcoins, visit LocalBitCoins.com and buy some.
OK, that made sense.  I don't have any bitcoins yet and have not yet invested in any mining hardware, so going someplace to buy some is necessary.
Then I started investigating the exchanges and how they work.
I'm accustomed to AmeriTrade.  I transfer money to AmeriTrade, they facilitate the buy-and-sale of stocks, etc.  Sellers know the money exists because Ameritrade has it and verifies it.  Buyers know they'll get what they're paying for because AmeriTrade has that, too.
However, that does not seem to be the case on LocalBitCoins.com.  It appears they don't want anything to do with escrowing the USD, only the BTC, and that appears to open them up to fraud.  It's one thing to hand my banking info to AmeriTrade, but to hand it to some one with a pseudonym who could be living anywhere in the world?
Question: What is the most reliable way to escrow cash before making a BTC purchase?
It almost appears there isn't any.  People seem to want either face-to-face cash delivery, mailed cash delivery, Moneygram or Western Union transfers (ugh, expensive), or even gift card solutions.  All of this appears, well, mickey-mouse to the extreme.  It's like the old west where no one is willing to be "the bank."

Remitano is another option. It is popular in certain countries. Check it.

Sites like localbitcoins.com (and eBay!) rely on reputation scores to assuage the type of concerns you express.
If a user on localbitcoins.com has a high number of succesfully completed transactions, with a 100% overall score, I think you can feel reasonably reassured that this user is reliable and will do the right thing. They have a respectable track record of performing as expected.
If you are buying bitcoins, in fact you do not have to give your fiat (dollar) banking information out at all. Many bitcoin sellers will accept cash, either in person, or deposited at their bank - so they would have to give you their banking information.  Unfortunately, many traditional fiat banks are restricting cash deposits into user accounts from anyone but the named account holder.  (Perhaps because they sense their obsolescence versus the security, speed and de-centralized nature of cryptocurrency.) So, verify that the bank you are depositing into will accept cash deposits from third parties.
There are other ways to pay for the bitcoins you are buying, as you point out, such as "Zelle" (https://www.zellepay.com/how-it-works) and others. Check the localbitcoin.com adds for the different ways sellers of bitcoin may accept payment.
Interesting that nobody wants to be "the bank". I think that is one of the beauties and reasons-for-being of crypto. There really is no need for banks, once you can receive, and send crypto on your own, from your own machine, with its own wallet. It obviates the need for third party intervention, really. Paying someone with crypto is like handing them cash, but it can be done electronically world-wide.
Maybe what you have here is a business opportunity for such an escrow company. One that will hold fiat deposits to secure transactions between seller & buyers. It would receive fiat from buyers of crypto, and release the funds to the sellers of crypto when it verifies (by monitoring transactions in the blockchain) that the agreed-upon crypto has been deposited into the buyer's crypto address...
Crypto funds are "kept" by the coin's entire peer-to-peer network in public addresses, and exist everywhere worldwide where any peer in the coin's network keeps a copy of the blockchain: aka, the shared-ledger which accounts for the creation and transfer of coins. But only the owner of the each address should have the private key that can spend the funds in that address.
(Make sure to keep the private keys to your addresses truly private !)
It's even possible to print out your private key on paper, and erase any trace of it from a digital device, making it impossible for any hacker to abscond with your funds. Cryptocurrency is very similar to cash in this regard. Your private keys are literally the keys to your funds. If someone takes or copies your private keys, they can spend your crypto funds. This would be analogous to leaving fiat cash lying around somewhere where it can be stolen.
Just keep those keys (in most wallet apps it's the 'wallet.dat' file in the .bitcoin directory) safe and secure and you will be fine.
Best of Luck

The answer really depends on your definition of "safety" in transactions. However, I assume you are looking for a similar escrow service in a stock exchange. Many businesses, huge ones in-fact, are competing with all sorts of colorful offers to get a share of that "banker" rule for the trading of crypto-currencies.
Despite many online sellers and buyers, these exchanges do not offer to buy or sell anything themselves; instead, everything in their business is based on offers of sell or buy from their customers. You'd be able to find many of them with a quick google search for "bitcoin exchange".
Just like your example of Ameritrade and what we know as "stock exchanges", crypto-currency exchanges are usually open to the public to trade crypto-currencies against each other and against regular money which is usually referred to as FIAT money in these exchanges.
They usually require their customers to properly identify themselves, and then transfer and deposit their money or their crypto-currencies to the exchange. Then they allow each customer with a positive balance, to place an offer to buy or sell a certain amount of another crypto-currency for a certain price of their choice and up to the available funds or bitcoins or crypto-coins of the customer. As a result, the exchange will have a live list of offers to buy and sell between pairs, like BTC/USD or ETH/BTC (for ethereum to bitcoin trades).
Exchanges maintain the list of offers and execute two opposite offers/orders against each other whenever the price tags match. They also usually keep their list of offers open to their customers and sometimes even to the public.
For example, if I transfer 1 BTC to an exchange, I can open a sell offer to sell up to 1 BTC for any price I want. Now if I open a BTC sell order for $10000/BTC while every other offer is for $10005+, I'd be on the top of the list of sellers. And if at the same time you open a buy order for $9999/BTC while all other offers are for less than $9995 per BTC, even though your offer would be on tp of the buyers list, nothing will happen until either of us change our mind to match the price of th other one. In this case, lets assume that you'd see the list of sell offers and realize that with adding only one dollar to your offer, it would match my offer. And lets assume, you'd do it. Then the following steps will happen:

The exchange will remove your offer and my offer from the list of offer and instead a transaction will be created for $10000/BTC and a volume of 1 BTC
$10000 will be deducted from your deposits in the exchange and will be added to my deposits
1 BTC will be deducted from my deposits and will be added to your deposits in the exchange
Depending on the rules of the exchange, one of us or both of us will pay a transaction fee to the exchange. The fee usually gets deducted from the deposited BTC or FIAT.
The current price of bitcoin will be announced as $10000/BTC in the exchange
... and finally, if we have used a big exchange, many sellers and websites will adjust their BTC prices based on the price of our trade as the last trade, or an average of the last couple of trades of one or more exchange.

Once you are satisfied with the status of your account, you'd be able to close all offers/orders and withdraw the balance on your account, like your bitcoins and remaining money to your bitcoin wallet and bank account.
Remember that the before withdrawal of your bitcoins, they would be remained in the wallet of the exchange. And the exchange transaction fee of exchange has nothing to do with the transaction fees of the bitcoin network. You'd have to pay the bitcoin transaction fees when you deposit or withdraw your bitcoins to and from the exchange. Most exchanges have some other fees for different methods of deposit and withdrawal.
And one last note: Always research the reputation and all rules and policies of the exchange before even opening an account.


text:
bitcoinrpc.authproxy.JSONRPCException: -26: 16: bad-txns-in-belowout
I am getting this exception, when I am using sendrawtransaction. And all I want to do is translate this docs to Python code, and I have searched for a while but both Can anyone shed any light on this error? Bitcore Multisig - bad-txns-in-belowout and Bitcoin core “bad-txns-in-belowout” can't make me clear. and all the exception traceback are list as below:
Traceback (most recent call last):

File "multisign.py", line 137, in
      print(ms.go())   File "multisign.py", line 128, in go
      ret = self.rpc.sendrawtransaction(last_hex)   File "/Users/frank/venv/bitcoin/lib/python2.7/site-packages/bitcoinrpc/authproxy.py",
  line 141, in call
      raise JSONRPCException(response['error']) bitcoinrpc.authproxy.JSONRPCException: -26: 16: bad-txns-in-belowout

Whole my python code as following:
import json
import binascii
from pprint import pprint
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_user = 'my_rpc'
rpc_password= 'my_rpc_password'
rpc_host = '192.168.1.86:9332'

rpc_connection = AuthServiceProxy("http://{}:{}@{}".format(rpc_user, rpc_password, rpc_host))

#print(best_block_hash)

class MultiSign(object):

    def __init__(self, rpc):
        self.rpc = rpc

    def validate_address(self, addr):
        ret = self.rpc.validateaddress(addr)
        return ret

    def pubkey(self):
        pass

    def set_addr(self, addr_1, addr_2, addr_3, addr_4):
        self.addr_1 = addr_1
        self.addr_2 = addr_2
        self.addr_3 = addr_3
        self.addr_4 = addr_4

    def create_multisig(self, nrequired, keys):
        """
        Deprecated this <createmultisig>

        @param nrequired: numeric
        @param keys: string A json array of hex-encoded public keys

        @return {"address":"multi_sign_address", "redeemScript":"script"}
        """
        return self.rpc.createmultisig(nrequired, keys)

    def add_multisig_address(self, nrequired, keys):
        return self.rpc.addmultisigaddress(nrequired, keys)

    def dumpprivkey(self, addr):
        return self.rpc.dumpprivkey(addr)

    def send_address(self, addr, amount):
        return self.rpc.sendtoaddress(addr, amount)

    def get_rawtransaction(self, txid, flag=1):
        return self.rpc.getrawtransaction(txid, flag)

    def create_raw(self, txid, vout, dest_addr, amount):
        pass

    def go(self):
        total_amount = self.rpc.getbalance()
        print(total_amount)
        utxo_vout = 0
        addr1 = self.rpc.getnewaddress()
        addr2 = self.rpc.getnewaddress()
        addr3 = self.rpc.getnewaddress()
        addr4 = self.rpc.getnewaddress() # destination address which we will send to
        raw_change_address = self.rpc.getrawchangeaddress()
        fee_obj = self.rpc.estimatesmartfee(6)
        fee = fee_obj.get("feerate")

        send_amount = total_amount / 2
        change_amount = total_amount / 2 -  fee
        print("send_amount -->%s" % send_amount)

        if change_amount < 0.00001:
            print(change_amount)
            raise Exception("Insufficient funds")
        change_amount = "%.8f" % change_amount
        send_amount = "%0.8f" % send_amount
        # ======

        data = "@landpack"
        if len(data) > 75:
            print("Data length is {}".format(len(data)))
            raise Exception("Too much data, use OP_PUSHDATA1 instead")

        hex_format_data = binascii.hexlify(data)

        # validate each address
        #pub_obj_addr1 = self.validate_address(addr1)
        #pub_obj_addr2 = self.validate_address(addr2)
        #pub_key_addr1 = pub_obj_addr1.get("pubkey")
        #pub_key_addr2 = pub_obj_addr2.get("pubkey")
        pub_obj_addr3 = self.validate_address(addr3)
        pub_key_addr3 = pub_obj_addr3.get("pubkey")
        # dump prive key ..
        priv_addr1 = self.dumpprivkey(addr1)
        priv_addr2 = self.dumpprivkey(addr2)
        priv_addr3 = self.dumpprivkey(addr3)
        # add multi sign address
        ret = self.add_multisig_address(2, [addr1, addr2, pub_key_addr3])
        print("==" * 10)
        print(ret)
        addr5 = ret.get("address")
        redeemScript = ret.get("redeemScript")
        #
        txid = self.send_address(addr5, send_amount)
        # check the transaction by txid
        ret = self.get_rawtransaction(txid, 1)
        vout_obj = ret.get("vout")
        scriptPubKey = vout_obj[0].get("scriptPubKey")
        hex_value = scriptPubKey.get("hex")
        # create a raw transaction
        ret_hash = self.rpc.createrawtransaction([{"txid": txid, "vout": utxo_vout}], {"data":hex_format_data, addr4: send_amount, raw_change_address: change_amount})
        # sign transaction
        sign_raw_transaction = self.rpc.signrawtransaction(ret_hash, [{"txid":txid, "vout":utxo_vout, "redeemScript": redeemScript, "scriptPubKey": hex_value, "amount": send_amount}],[ priv_addr1])

        # ..
        party_hex = sign_raw_transaction.get("hex")
        sign_party_transaction = self.rpc.signrawtransaction(party_hex, [{"txid":txid, "vout":utxo_vout, "redeemScript": redeemScript, "scriptPubKey": hex_value, "amount": send_amount}],[ priv_addr3])
        # send to brodcas
        last_hex = sign_party_transaction.get("hex")
        print(sign_party_transaction)
        ret = self.rpc.sendrawtransaction(last_hex)

        return ret

if __name__ == '__main__':
    addr = 'tb1qffcx4mpft5lxk9clsz2du4t03elxl4qwx2hu8z'
    ms = MultiSign(rpc=rpc_connection)
    ms.validate_address(addr)
    print(ms.go())

That error means that you are trying to spend more money than you have inputs for. In other words, value in < value out. You need to add more inputs so the total input value exceeds the total output value.
You need to get unspent outputs from previous transactions which you have received at the address your trying to send from. Have a look at listreceivedbyaddress from blockchain.info api.

Well, I have tried to get the balance by total_amount = rpc_connection.listunspent()[0], but still show me the same exception.

Can you share some of the output the other print statements? It's hard to debug without knowing the balance, and what the raw transaction looks like.


text:
How to build a bitcoin delegation server?
Actually, I know there are already have blockchain.info and its own api. But I want to build my own server which can provide basic API like:

Generate a wallet by use password and username.

User can login/logout(Optional)

User can do transaction (send/receive to/from someone's address)

But, I have google for a while. The only way to create a wallet is configure the bitcoin.conf before run the bitcoind server. I don't know how can this works, I know there are also a way call multisig, But I don't know how to connect it with the wallet. I mean how to make each user has his/her own wallets.
Anyone help?

Let's break it down a little.
Things you need a node for:

Receiving new transactions and blocks
Indexing transactions
Building transactions
Broadcasting transactions

Things you don't need a node for:

Generating keys
Signing transactions

You could, in theory, just build a program that generates your keys and multisig redeem scripts, and converts them to addresses for your users. Then, you can use insight or blockchain.info or any one of several explorers to look up transactions for the addresses you generate, and build outgoing transactions.
Once you have the outgoing transaction, your program can sign it with the keys you previously generated, and then broadcast it via an explorer API.
Alternatively, you could run your own bitcoind node, and index incoming transactions yourself.
A wallet and a node are two separate concepts. Bitcoind can act as both, but it's core function is that of a node. Many people run bitcoind with absolutely no keys on it, and use light clients like Electrum or hardware wallets to store their actual BTC.

Could you please draw an architectural diagram, I really newbie at this area.

It's not possible to design an architecture without a lot more detail, and that's unfortunately more effort than I'd be willing to put in on a volunteer site. There are too many different ways you could build this.

Oh, I understand how's going on. because I still believe there are must be need a centre server exists. I have review your answer and got your point! I want to build a DAPP instead a normally app! Thanks bro.

You'll need to be running a full Bitcoin node and on top of that some sort of API that stores information on blocks/transactions/addresses in a database (e.g. the insight api).
You could then have another API on top of that handles wallet generation and key handling (something like Bitcore Wallet Service).


text:
How do I know one transaction has confirmed?
I am running my bitcoind with -zmqpubhashtx optional, and I receive notification once a new transaction has broadcast to public chain! I can also parser it by getrawtransaction and decoderawtransaction. But I couldn't validated if a transaction is confirmed.
Additionally, there are also exists an optional name as -zmqpubhashblock, I can also parser it by getblock and read its all transactions, compare it all with my MySQL data, if it's exists with the same txid, I'll update my column (confirmations to plus one), but it's a little bit ineffective.
Let's say, After I ran getblock <hash>, and then give me a tons of transaction. and I have to check each something like:
UPDATE t_unspent_tx
SET confirmations = confirmations + 1
WHERE addr in (addresses)

BTW, Can I trust the block hash from notification? Is it may not be the longest on the chain?
PS, I don't want to check confirmation from the blockchain.info or some other site else.

If you have txindex=1, you can call getrawtransaction <txid> 1 to receive a decoded tx object, which will include the number of confirmations and the blockhash.

Oh! I am definitely sure there is no confirmations after you decode the hex, which get by getrawtransaction.

Seems to work on chainquery. What version of Bitcoin are you running?

I am using the V0.16.1 version. The link that you given should be processed.

It also seems to be in the source. Not sure why it won't show up on your local node. Are you sure you're using getrawtransaction, and not decoderawtransaction?

Oh! getrawtransaction only return me a hash, and I have to use decoderawtransaction to parser it.

getrawtransaction has a verbose mode, as described in my answer, use that instead


text:
How to move sync's data to another partition after run Bitcoind for a while?
I have download a new bitcoin package from official site. And then I ran it with daemon mode also with default configuration (Default means not bitcoin.conf file was created in ~/.bitcoin/.bitcoin.conf). After ran 2 hours. I got stuck, and the process exit. When I checked my disk with:
df -lh

And then, I got those:
Filesystem      Size  Used Avail Use% Mounted on
/dev/vda1        20G   20G  118M 100% /
devtmpfs        3.9G     0  3.9G   0% /dev
tmpfs           3.9G     0  3.9G   0% /dev/shm
tmpfs           3.9G  233M  3.6G   6% /run
tmpfs           3.9G     0  3.9G   0% /sys/fs/cgroup
/dev/vdb        800G  7.7G  792G   1% /data
tmpfs           783M     0  783M   0% /run/user/1000
tmpfs           783M     0  783M   0% /run/user/1001

And I googled for a while, but could't find a good way to move all sync's data to the /dev/vdb. I understand what my mistake came from, but I just fixed it by move data and then put a new configuration with --data-dir=/dev/vdb. and then keep sync it.
So, How do I reach that?

Rather than adding —data-dir to the config file, try starting bitcoind by running bitcoind —data-dir=[your directory] [whatever other commands you want to run].

@chytrik Did you mean run the bitcoind with --data-dir like ./bitcoind --data-dir=/data ?

^yea! Sorry I accidentally submitted my comment half-written, and had to edit to add the rest. Mobile keyboard problems :p

Anyway, Thank you so much. And could you also point me how to move the old data to the new place?

best way on unixoide systems to copy data over different media is rsync in a terminal. I usually go "rsync -rpogDtW <source_dir> <target_dir>". Further details are not bitcoin relevant, and should then be asked in another stackexchange forum.

I have try to ran the bitcoind -data-dir=/data/db -daemon , but it's not write the data to the path where I specify. Actually, The right way to do that with :
bitcoind -datadir=/data/db -daemon

Attention
   -data-dir --> -datadir


text:
What's the best way to store unspent transaction?
AFAIK, To send a raw transaction, which include both input and output. And What if we run it on the local node, we can simply fetch the unspent list by run bitcoin-cli listunspent, but If I just want to create a raw transaction on the client side, I believe the only way it store all the transaction to my local server. and before store it, I should do the following operations:

1.get raw transaction (getrawtransaction)
2.parser raw transaction (decoderawtransaction)
3.get the value of amount, and transaction id
4.put all together insert it into the mysql database

The table struct as :
mysql> desc t_tx;
+---------------+---------------+------+-----+---------------------+-------------------------------+
| Field         | Type          | Null | Key | Default             | Extra                         |
+---------------+---------------+------+-----+---------------------+-------------------------------+
| txid          | char(64)      | YES  |     | NULL                |                               |
| vout          | int(11)       | YES  |     | NULL                |                               |
| address       | char(35)      | NO   | PRI | NULL                |                               |
| redeemScript  | char(44)      | YES  |     | NULL                |                               |
| scriptPubKey  | char(46)      | YES  |     | NULL                |                               |
| amount        | decimal(16,8) | YES  |     | NULL                |                               |
| confirmations | bigint(20)    | YES  |     | NULL                |                               |
| spendable     | char(8)       | YES  |     | NULL                |                               |
| solvable      | char(8)       | YES  |     | NULL                |                               |
| safe          | char(8)       | YES  |     | NULL                |                               |
| blockhash     | char(64)      | YES  |     | NULL                |                               |
| created       | timestamp     | NO   |     | current_timestamp() | on update current_timestamp() |
+---------------+---------------+------+-----+---------------------+-------------------------------+

The table look so redundancy, I guess there are many columns I can remove from my table.
Look the output as below, If your guys can get a comment to each field at the end will be a really good for everyone, as I do at the end of txid.
[frank@localhost bin]$ ./bitcoin-cli decoderawtransaction 0200000001dbceae939bd37f2fe9dff0fca2aeaf44ec4987a34d59d58012982f49248d78fa0000000049483045022100f49a4e30e3baa5f00119f20e12a9bc932eea0814f7841ce0dc0ac17808d17e6e02207a50138fd23e7ac951fec96ff9869ecfbd495504889163a6d351ca07d2385de801feffffff02d8b068590000000017a914f393140f96b131c20ab063f025694dcade19e21e8700ca9a3b0000000017a914fc5d7d9af26be5f5656ac88023d1ff1683212dcc8737010000
{
  "txid": "172b99d21c02430fa16a70883d10090fde39c087ca82ebdf5a1b2567b115272e", // transaction id
  "hash": "172b99d21c02430fa16a70883d10090fde39c087ca82ebdf5a1b2567b115272e",
  "version": 2,
  "size": 188,
  "vsize": 188,
  "locktime": 311,
  "vin": [
    {
      "txid": "fa788d24492f981280d5594da38749ec44afaea2fcf0dfe92f7fd39b93aecedb",
      "vout": 0,
      "scriptSig": {
        "asm": "3045022100f49a4e30e3baa5f00119f20e12a9bc932eea0814f7841ce0dc0ac17808d17e6e02207a50138fd23e7ac951fec96ff9869ecfbd495504889163a6d351ca07d2385de8[ALL]",
        "hex": "483045022100f49a4e30e3baa5f00119f20e12a9bc932eea0814f7841ce0dc0ac17808d17e6e02207a50138fd23e7ac951fec96ff9869ecfbd495504889163a6d351ca07d2385de801"
      },
      "sequence": 4294967294
    }
  ],
  "vout": [
    {
      "value": 15.00033240,
      "n": 0,
      "scriptPubKey": {
        "asm": "OP_HASH160 f393140f96b131c20ab063f025694dcade19e21e OP_EQUAL",
        "hex": "a914f393140f96b131c20ab063f025694dcade19e21e87",
        "reqSigs": 1,
        "type": "scripthash",
        "addresses": [
          "2NFT8P5jxEGhSMY1xGqpADyPztK3pmh5pWb"
        ]
      }
    },
    {
      "value": 10.00000000,
      "n": 1,
      "scriptPubKey": {
        "asm": "OP_HASH160 fc5d7d9af26be5f5656ac88023d1ff1683212dcc OP_EQUAL",
        "hex": "a914fc5d7d9af26be5f5656ac88023d1ff1683212dcc87",
        "reqSigs": 1,
        "type": "scripthash",
        "addresses": [
          "2NGFcGUAUd9KyMpCJhqVZPfJ2mTi1rLvTtU"
        ]
      }
    }
  ]
}

As we know, the createrawtransaction function require an input and an output. but both input and output are array type, which means you can put more than one unspend transaction as input, and more than one dest address with amount into the output. but if I just want to create the raw transaction and sign it at the client side (mobile app), I need the node server support with api, which can call with an address and response all the unspent back!
I have tried all the command from bitcoin-cli, but non of them are useful at the scenes. so I want to subscribe the node information by zeroMQ, and then parser the txid by (getrawtransaction & decoderawtransaction), and then store all the related information into the mysql. But I don't know how to make this happend, because I have a little be confuse with the output from decoderawtransaction, and one can explain each field means? Especially, the vout inside the vin.
BTW, if you in think my solution is bad, please correct me, I am really newbie at the bitcoin!

To create a new transaction (with createrawtransaction) you will require a previous unspent vout - i.e. a UTXO, which is the result of the listunspent command. This will be the input of the transaction. The output of the transaction will be created on the fly, based on the amount and destination address. A transaction fee is likely necessary, and is calculated as tx fee = (sum of inputs) - (sum of outputs). Note that miners discriminate transactions based on the fee/vbyte, so a larger transaction (byte-size, not btc spent) needs a higher fee to be competitive.
The only thing you will need to store in your database is the vouts, indexed with the address or script hash. On each new block you will have to update those vouts, removing the ones that have been spent and add new unspent ones.

Can you indicate which part should I parser and store it in my sample output ?

The things you need to store for a vout is the txid and the output number(n). Also you need to store the address/scripthash so that when a client queries for specific keys he gets the required results.

Then when you create a new transaction you only need to provide 'txid' and 'n'.
The client though also needs to sign this 'vin' with the private key corresponding to this script/pubkey address.

Could you provide me some example, I really newbie at the bitcoin :)

http://chainquery.com/bitcoin-api/createrawtransaction
\n
https://en.bitcoin.it/wiki/Transaction

Edit: transaction fees are not included as a vout, they are simply included as an excess of input value compared to outputs.

@NikosKostoulas Sure, I can store every transaction into the mysql. But as the HD wallets exist, I can't figure which address belong to the same account. Let's say, If Alice have 20 BTCs, and she send 8 BTCs to Frank, and get 12 BTCs back to a change address, I don't know how to group those unspent . Anyone suggestions in your answer?

The unspent contains a scriptPubKey where btc was paid to. It also contains an address. It's these address you need to use to store the unspent with. Alice should be able to look up her own unspent based on the addresses stored on her wallet.


text:
Signature must be zero for failed CHECK(MULTI)SIG operation
Firstly, let me show my version:
[frank@localhost bin]$ ./bitcoin-cli -version
Bitcoin Core RPC client version v0.16.1

After sendrawtransaction and I got:

error code: -26 error message: 64: non-mandatory-script-verify-flag
  (Signature must be zero for failed CHECK(MULTI)SIG operation)

And then, I try to decoderawtrsanaction the hex, and then I got the following output:
[frank@localhost bin]$ ./bitcoin-cli -regtest decoderawtransaction 020000000001018cc2f3c4f1af3ad60f3f3dcf5e3c3bfadb824e22aadec877f5a2bc4f99029dab0100000017160014c21bbdc4a642e391a6401bf30ac3e4e8e9669ea2ffffffff01605af4050000000017a914317fec65edbff6e4350fbe668cfedaf54ea9061587024730440220288b7912b6f6c0734ee34cada2c20fc81e8a7e11b4ccc9285b204eb25da953fa02205040878b44db8b17c8d62822c9124a4b154b46ccbd321fddfd52b9acd6742e1f032102efff391c5baf1433e2c488271ceebaa6eb2a203000ff62320de13d07b1ec4f4c00000000
{
  "txid": "42f6612dedacb4b5a24ffb75c07ae61eb939bb40c039fb165284bbac516b1e78",
  "hash": "6db7c04b006407655f55f2e64057d6ced61d34ee9b96ae9bcf5ead6dc311ecaf",
  "version": 2,
  "size": 215,
  "vsize": 134,
  "locktime": 0,
  "vin": [
    {
      "txid": "ab9d02994fbca2f577c8deaa224e82dbfa3b3c5ecf3d3f0fd63aaff1c4f3c28c",
      "vout": 1,
      "scriptSig": {
        "asm": "0014c21bbdc4a642e391a6401bf30ac3e4e8e9669ea2",
        "hex": "160014c21bbdc4a642e391a6401bf30ac3e4e8e9669ea2"
      },
      "txinwitness": [
        "30440220288b7912b6f6c0734ee34cada2c20fc81e8a7e11b4ccc9285b204eb25da953fa02205040878b44db8b17c8d62822c9124a4b154b46ccbd321fddfd52b9acd6742e1f03",
        "02efff391c5baf1433e2c488271ceebaa6eb2a203000ff62320de13d07b1ec4f4c"
      ],
      "sequence": 4294967295
    }
  ],
  "vout": [
    {
      "value": 0.99900000,
      "n": 0,
      "scriptPubKey": {
        "asm": "OP_HASH160 317fec65edbff6e4350fbe668cfedaf54ea90615 OP_EQUAL",
        "hex": "a914317fec65edbff6e4350fbe668cfedaf54ea9061587",
        "reqSigs": 1,
        "type": "scripthash",
        "addresses": [
          "2MwkxLxbgdZKGEN4fS8GQATqQGXyRpFbkuf"
        ]
      }
    }
  ]
}

I don't know what I missed? Any one know?

Are you on regtest? I didn’t see previous tx on testnet explorer... What command was used to create the raw tx? I also can see only one signature, is it the funding transaction?

ah, yes, regtest... check that previous tx was not spent already, and maybe search the forum here for the word "mandatory" - this reveals several similar errors. Still I'd be interested to know, how tx was created (you may edit your post)...

Yes, I run on regrets. I just simply listunspent and picks a transaction with only one confirmed. I followed the official guide, so I don't how to figure out.

I still can't see how the multisig came into the game. bitcoin.org developer section guide? Or this from Gavin? https://gist.github.com/gavinandresen/3966071 - and here is similiar problem, with steps and solution in comments section: https://bitcoin.stackexchange.com/questions/69935/unable-to-broadcast-native-p2wpkh-segwit-tx-malformed-but-how