text:
How to create block height to UNIX time converter?
I want to create a converter that can be given a block height, human readable time, or UNIX time and then provide the correlated information for it. For example, if given a block height, the converter will give you an estimated time (UNIX and converted to human readable format). And the same if given a UNIX time, it'll provide block height and human readable time associated with that block. And so forth if given a human readable string (stretch goal).
However, looking at the information online it seems pretty lack luster and also very approximate, using formulas, etc. See links here of similar questions:
https://ethereum.stackexchange.com/questions/10576/calculate-approximative-block-height-at-a-certain-time
https://www.reddit.com/r/BitcoinBeginners/comments/87lr89/is_there_any_block_height_to_datetime_converter
Are there any methods that could be achieved to create a deterministic result?
One method, I am considering is to iterate through the blockchain and generate a database that stores the block height and the UNIX timestamp associated in the block header of the block. Would this be a proper solution to the problem?

In theory there is one block per 10 minutes. That means you should be able to approximate the time of a block n as FIRST_BLOCK_TIME + n*600, where FIRST_BLOCK_TIME is the time of the genesis block, 1231006505.
Of course, that's very approximate, as the average time per block has been consistently less than ten minutes due to increasing block difficulty. In fact, as of writing (block 622719 with timestamp 1585016395), is 19621510 seconds earlier (over 7 months) than what would be predicted by that formula.

One method, I am considering is to iterate through the blockchain and generate a database that stores the block height and the UNIX timestamp associated in the block header of the block. Would this be a proper solution to the problem?

Using the real data is obviously going to be better than any approximating formula. Note that the timestamp of blocks are not necessary the actual time they are mined (in normal circumstances they can be up to 2 hours in the future, and up to approximately 1 hour in the past).

Hmmm... what is the time that everyone in the network agrees to? I guess I care about "network time" given your last statement of +2hour/-1hour accuracy. Thank you for your response.  It would be nice however to get a more accurate UNIX time but I'll work with what is given. I just want it to be consistent and deterministic.

There is no time agreed upon by the network but the block timestamp. It's wildly inaccurate, but not wrong, and it's more than enough for its purpose of existing: adjusting difficulty.

OK - appreciate the input!

Hi is the time provided by the RPC call GetBlock the timestamp of the block in question?  "time" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT) https://bitcoin.org/en/developer-reference#getblock

Yes, that's the block's timestamp.

Thank you. And I am slightly confused by your 2nd paragraph, characterizing increasing block difficulty as time between blocks should be correlated with increasing average time between blocks (or set it to the intended 10 minute between blocks). Are you implying that time between blocks has consistently been less than 10 minutes (in this case 1 minute) due to hash-rate outpacing the difficulty formula?

Correct. The average block rate over all time is around 1 block per 9.5 minutes.

Currrntly, more than 12 minutes.

@LeanMan re: "what is the time that everyone in the network agrees to?" - the blockchain is the clock, each new block is like one tick forward.


text:
What bitcoin data should I back up?
I have an Electrum bitcoin wallet on my PC. If my house burns and my PC is destroyed and the seed (written on paper) is destroyed, my bitcoins are lost. I want to prevent this situation.
What is the best I can do?

Storing the wallet file on another server (not possible with Electrum)
Export the private keys - address combinations and storing them AES256-encrypted on another server.
Storing the seed AES256-encrypted on another server.
something else?

Since Electrum is a deterministic wallet having a copy of the seed is sufficient to get access to the coins. However if you also want to be able to restore the meta data in the wallet file such as the transaction and address labels and your contacts you need to periodically backup the wallet file too.
You can save a backup copy of your wallet file via file menu > save copy. Alternatively you can have your backup program grab the wallet file from the wallets directory.
If you're worried about your house burning down then do as @willtech says and keep a backup of your seed and/or wallet file in an off-site location. Cloud backups of your password protected wallet file are another option.
Note: Electrum doesn't store your wallet file, seed or private keys on any server.

I have not used Electrum but understand your ability to do essential backups you may do with some other software may be somewhat limited by the way that the Electrum software operates.
The simple answer is, store a copy of your seed recovery passphrase in a safety deposit box or at some other secure offsite location.

source: Stack Exchange

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

sort: votes


text:
Who is responsible for ensuring that the bitcoin protocol is not violated in the network?
Who is responsible for ensuring that the bitcoin protocol is not violated in the network?

The market forces behind the supply and demand of bitcoin
Miners
Consensus of the miners
Developers of the bitcoin protocol

There is no single entity responsible for ensuring the rules of the protocol are not violated. Rather, bitcoin is a decentralized network, so all participants must adhere to the protocol’s rules, or else the network will ignore them.
This is accomplished by a network of full nodes, that relay and validate all transactions and blocks against the network’s rules. All of the nodes together form the decentralized network, so to join the network you must adhere to the rules defined by the node’s code.

The market forces behind the supply and demand of bitcoin

This will determine the price, but the price will not affect the ability of participants to violate the networ’s rules, nor will it ensure that rules are not violated. The rules must be followed whether the price is $1 per bitcoin, or $1 million per bitcoin.

Miners

Miners work to secure the blockchain record, they will validate transactions in the same way other (non-mining) full nodes do, and they will ensure only valid transactions are added to the blockchain.

Consensus of the miners

Same as above. Note that even if a group of miners decided to violate the network’s rules, then the network (full nodes) would simply ignore any new (invalid) blocks found by those miners.

Developers of the bitcoin protocol

The developers collaboratively write and refine the code that runs the network, but this does not give them absolute powers to violate or change the rules. Their code works to ensure that everyone involved in the network is behaving, and that any misbehaving nodes are banned.

Bitcoin is a decentralized. Therefore, there is no central regulatory governing/policing person or group responsible for the proper usage of bitcoin.
No person, group or country controls the entire BitCoin or BlockChain network.
Let me know if that’s not clear or further detail is needed.
Cheers

hello thank you, What about if you were to choose from the below options:
1. The market forces behind the supply and demand of bitcoin
2. Miners
3. Consensus of the miners
4. Developers of the bitcoin protocol
So, which one is responsible for ensuring that the bitcoin protocol is not violated in the network?

No one is responsible for ensuring the BitCoin protocol, unless perhaps you’re referring to the developers in the development stage of bitcoin could be considered responsible for making sure the protocol was coded in such a manner as to prevent violation; but once it was released there is no one person, groupOr government agency that is responsible for it bitcoin violations

Now if there are laws broken during the violation of Bitcoin protocol which you’re referring the lawn Forssman or government agency who handles the laws that were broken during the violation could be deemed responsible for investigation and prosecution of the crimes committed during the bitcoin protocol violation. E.g. Someone hacked into a server in the United States and steals bitcoins law enforcement is responsible to investigate and prosecute The laws violated within their jurisdiction that were broken during the theft

Hope that’s helpful please let me know if perhaps I’m not understanding your question in the terms you had in mind when you asked. Cheers

@Joey I am sure that the programmers would explain that they program the consensus, that Bitcoin Core (the reference client) is deterministically programmed. Blocks will not be accepted by the client if they break protocol rules so, not the miners' consensus.

So does the BitCoin core, as you described, ensure the BitCoin protocol is not violated in the network?

And if so, has it prevented all violation of BitCoin protocol in the network?

I would assume that he market forces behind the supply and demand of bitcoin are responsible as users actually decides which bitcoin protocol to use?

supply and demand, market forces, bitcoin users, etc....do not have any control over enforcing bitcoin protocol violations.

Case in point: stolen bitcoins is a daily occurrence, and it cannot be stopped; it can mitigated but not controlled to the point of elimination.

Bitcoin Core ensures that the protocol is not violated at the installed node, at each installed instance of Bitcoin Core. Yes, it has many times rejected blocks because they violate the protocol, e.g. a block contains a double spend. Nodes often reject transactions from the mempool before they even reach a block. Also, with some forks of Bitcoin, the forked client runs alongside the Bitcoin network using a fork on the blockchain and their invalid for Bitcoin transamissions are also routinely rejected.

That's a big part of the point of bitcoin... it's not just one entity, it is everyone ensuring the rules are followed.

“Rather, bitcoin is a decentralized network, so all participants must adhere to the protocol’s rules, or else the network will ignore them”
So if the network were to ignore the actors involved in the theft of Bitcoins stolen through bitcoin protocol violation, amongst many other methods, will this have the result of preventing any further violation of protocol by the group responsible for its initial successful theft through its violation? No!

I am not aware of any Bitcoin theft through protocol violation, but I am interested if there has been. Do you have any links or references?

No, Im sorry I don’t have any references for you. My comments stem from my experience as an it security engineer with a background in investigation and prosecution of digital crimes against banking and credit card institutions; In recent years I’ve had many discussions with many it security engineer, digital forensic investigators, who specialize and have been tasked with the investigation into crypto currency theft. I’m told that protocol weakness has been leveraged in several large scale crypto currency thefts.

The protocol itself has not caused any known thefts of Bitcoin. Rather all large scale thefts of cryptocurrencies have been errors by the implementors of custom software used as backends (or even frontends) of various services. There have also been a few social engineering attacks. But these are not related to the protocol itself; rather they are the result of poorly written custom software and human error.

If a group were to steal Bitcoin, the rest of the network will ignore them. What they stole would not be Bitcoin because it will result in a hard fork of the blockchain. So what they stole would be worthless.

Completely false.

@BeepBopBoom  I encourage you to research past bitcoin thefts, as others have mentioned none of them have happened because someone successfully violated the protocol’s rules, or exploited a security weakness in the protocol itself. AndrewChow covered the nature of some of the attacks that have happened well (software implementation errors, etc).

@BeepBopBoom please also note that on StackExchange an ‘answer’ post should address the main question, not another one of the answers. Your post here would have been better suited as a comment on my answer. SE is designed to be a community-built Q/A posting board, not a discussion board/forum.

Is it safe to say that there is a general consensus amongst you and the “others” you’ve spoken to about this, that there has never been any theft of bitcoins, which was achieved by leveraging an aspect of the protocol, as a part  in the process of the overall method utilized?

@BeepBopBoom there have certainly been thefts, but none are the fault of the protocol. All* transactions require a valid signature to prove their validity, and only the owner of the coins has the key required to sign, so the protocol would deem any other transaction of those coins as invalid

All the decentralized miners are responsible, as it is defined in the Bitcoin white paper. Noone else.

Its not just the miners. Users cannot blindly trust the miners.

@MeshCollier what are you taking about, have you read the white paper? That's the whole point if PoW.

Of course, but all users must verify that miners obey the rules too. Otherwise the proof of work is invalid. Don't trust, verify.

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


text:
How to recover wallet by importing private key on testnet?
I want to test the functionality of wallet recovery via private key import on the testnet. Preferably thru an online service.
I only want to test the functionality so that I can verify that it's basically working since I'm working on some Python code that I want to use on the mainnet later.
So for that, I don't want to download the whole blockchain but instead, want to verify that my private key is generated correctly and I can access the funds that way. But I can't find any possibility to do that on testnet...
EDIT: I did not use mainnet for anything yet. I'm exclusively used testnet to create the wallet and get some coins and want to verify on testnet the wallet recovery thru private key

Testnet uses a different address format than mainnet, you can not view or verifying anything about the mainnet on testnet, they are separate.
You can test your method from the origin by using testnet funds instead.
Alternatively, you can test on mainnet with a small amount of funds to confirm your recovery method is working the same as it did on testnet (which it should).

Why do you think that i want to view / verify something from the mainnet on testnet? I created a wallet on testnet out of some Python code and want to recover that wallet on testnet from the private key i got while creating the wallet. If that works, i will use mainnet.
I fail to see why i should test my implementation on mainnet with a small amount of BTC if there is explicitly testnet for such things

Please see additional comment in the question.

Endogen, you will need to provide more details on what you mean by recover a wallet with a private key. A private key is only a private key to a single bitcoin address, not a wallet. A wallet holds many private keys. Are you referring to your recovery words or an extended private key? Additionally I'm not sure why you are set on using an online service for your implementation, private keys should never be shared. You can recreate most wallet features through available libraries on your own, there's no need to use an online service for wallet recovery.

Thanks for the comment. 1) I would want to use the private key for an address 2) Online Service: Because for testnet, i find it convinient. Just want to verify that the key can recover the address, i don't want to download the chain. I want to verify just this one time that it works, never again. No need for privacy here 3) Recreating with libs: ok but how to be sure that i recovered the address correctly? Thus i wanted to hopefully see the correct balance for that address - doesn't work without downloading the chain?

You can code some function as fund transfer, from which library you're using in python you have to sign the transaction through private key, create two testnet addresses and transfer some funds by using a faucet like testnet-faucet
to one of them, then code a function for transferring funds to another address, this method should return a raw transaction hex, if you able to generate transaction hex then you can confirm that your private key recovery functionality works

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


text:
If BTCUSD Price Drops Far Enough Are Transaction Fees Enough Incentive for Miners?
There are some media reports that state that if the BTCUSD exchange ratio drops far enough, say below $5k per BTC, that mining will no longer be profitable. But, I do not see how this makes sense given that once bitcoin reaches 21 million coins the incentive for miners is limited to the transaction fee.
Wouldn't the transaction fees for mining simply go up to cover the cost of mining?

Wouldn't the transaction fees for mining simply go up to cover the cost of mining?

No, it wouldn't. Transaction fees are not related to the exchange rate. They are only related to the supply and demand of available block space. If not many people are transacting and blocks are not full, then there is an excess supply of block space and not a lot of demand for it. This will drive fees down, regardless of the exchange rate.
If the exchange rate were low enough that the block reward is not sufficient (regardless of the block subsidy existing), miners would simply stop mining. This will eventually reduce the cost of mining such that those who are still mining will become profitable again.

If the exchange rate were low enough that the block reward is not sufficient (regardless of the block subsidy existing), miners would simply stop mining. This will drop down the security of blockchain and break the whole crypto pyramide.

Downvoted: if the price drops and miners drop off, the difficulty will eventually adjust and the system will find a new balance. It was once profitable to mine bitcoin at $50, if the price dropped there is no reason that balance could not be found again. Your answer makes it sound like balance could not be found, and cryptocurrency would be ‘broken’.

balance definetely could be found. at zero level :) you are welcome to downvote everything you do not like

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


text:
Creating a Bitcoin address using the 9 steps. Stuck on stage 2
I need to write a script using C++ and the OPENSSL library that takes this: 0250863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352
performs a SHA256 Hash using the sha256 function from the OpenSSL library and then returns 0b7c28c9b7290c98d7438e70b3d3f7c848fbd7d1dc194ff83f4f7cc9b1378e98 as the digest.
The issue I am having is that I get a different message digest after performing the sha256 hash function: a9ce83de3a0ff3516b7c50cdd787e9f69f152f227d93c9512774231e7132e925.
I've been stuck on this for about 2 weeks and from my research I have been told that my function is not doing the right conversion of my message before performing the Sha256 hash function.
Code
string sha256(const string str)
{
  unsigned char hash[SHA256_DIGEST_LENGTH];
  SHA256_CTX sha256;
  SHA256_Init(&sha256);
  SHA256_Update(&sha256, str.c_str(), str.size());
  SHA256_Final(hash, &sha256);
  stringstream ss;

  for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
  {
    ss << hex << setw(2) << setfill('0') << (int)hash[i];
  }
return ss.str();
}

int main()
{

  cout << endl;
  cout << sha256("0250863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352") << endl;
  return 0;
}

could you specify to which 9 steps you are referring to? From a book or a guide somewhere online?

here is a good cross reference page with the 9 steps: http://gobittest.appspot.com/Address - when you deal with hashings in bitcoin, you must make sure that you hash the hex data, not the (ASCII) strings. I don't know ow to do this in C++, I had the problem in my shell codings with openssl...

The problem is that you are hashing the string of hex characters instead of the actual bytes that the hex string represents. You should be using an array instead with the bytes specified. The following should work:
string sha256(char[] str, size_t len)
{
  unsigned char hash[SHA256_DIGEST_LENGTH];
  SHA256_CTX sha256;
  SHA256_Init(&sha256);
  SHA256_Update(&sha256, str, len);
  SHA256_Final(hash, &sha256);
  stringstream ss;

  for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
  {
    ss << hex << setw(2) << setfill('0') << (int)hash[i];
  }
return ss.str();
}

int main()
{
  char[] arr = {0x02, 0x50, 0x86, 0x3a, 0xd6, 0x4a, 0x87, 0xae, 0x8a, 0x2f, 0xe8, 0x3c, 0x1a, 0xf1, 0xa8, 0x40, 0x3c, 0xb5, 0x3f, 0x53, 0xe4, 0x86, 0xd8, 0x51, 0x1d, 0xad, 0x8a, 0x04, 0x88, 0x7e, 0x5b, 0x23, 0x52};
  cout << endl;
  cout << sha256(arr, 32) << endl;
  return 0;
}

I've tried the code above, and after correcting my own syntax errors and getting it to compile I still get a different hash digest than I was expecting. the message digest I have is:                                                                           cf2bafdb95b6354a89afdbc7b9c7d5bfb53d9ace57518ccc05c3bd493dbe4bb4

I found this resource online after doing some further research . http://www.fileformat.info/tool/hash.htm?hex=0250863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352        So it seems like if I do a Binary Hash I get the message digest I am looking for, so I think what I have to is find a way to do a binary conversion on the hex representation to get the message digest I am looking for. Thanks Again for your help.


text:
bcoin example conf file?
Hey I've been looking around for an example conf file and I can't find one. I'm not sure how to put some parameters in. Do I do
prune=True
Or
prune
as in the documentation it says 'default: false'

I found it at the bottom of some documentation
https://github.com/bcoin-org/bcoin/blob/master/etc/sample.conf
prune: True


text:
ELI5: What is Base58Check encoding?
I've seen posts on how to do it and I've read the wiki on what it is, however these explanations are too complex. Can someone explain what it is and why it's called Base58Check encoding? Are addresses generated without going over those steps still valid in Bitcoin?
This is the explanation provided by the original bitcoind client in base58.h
// Why base-58 instead of standard base-64 encoding?
// - Don't want 0OIl characters that look the same in some fonts and
//      could be used to create visually identical looking account numbers.
// - A string with non-alphanumeric characters is not as easily accepted as an account number.
// - E-mail usually won't line-break if there's no punctuation to break at.
// - Doubleclicking selects the whole number as one word if it's all alphanumeric.

To further this question, what do npm packages like bs58check do exactly? The description is as so

A straight forward implementation of base58check extending upon bs58.

Base58check = checksum + base58

Can someone explain what it is and why it's called Base58Check encoding?

There are two parts to the name "Base58Check". The first part is "Base58". This is fairly self explanatory, the encoding uses Base 58. This means that there are 58 digits which are represented by 58 characters. One digit is a number between 0 and 57, just like how in the decimal system (or base 10) we have which are a number between 0 and 9. Since each digit is supposed to be one character, we need to have a different "alphabet" for each digit. For base 58, we use the alphabet 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz with the number 0 being represented by the character 1 and the number 57 represented by the character z. For comparison, the decimal alphabet is 0123456789 with the number 0 represented by the character 0 and the number 9 represented by the character 9.
The second part of the name is "Check". This refers to a checksum. The SHA256 double of the data that we want to encode is calculated, and the first four bytes of that hash is used as a checksum. This is an error detection method to help ensure that the data we received is correct and not corrupted. Those four bytes are appended to the data that we are encoding before we perform a base conversion to generate the base 58 string.
As with any piece of data in a computer, the entire pre-base58 byte string can be interpreted as a very large integer. From there, it is easy to perform a base conversion to base 58 and thus produce the final base 58 string.

Are addresses generated without going over those steps still valid in Bitcoin?

You cannot generate an address without going over those steps, so it is impossible to not go over these steps to produce an address.

To further this question, what do npm packages like bs58check do exactly? The description is as so

They implement the entire conversion from bytes to Base58Check encoded string.

123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz has 61 chars, isn't it?

@user218867 No, it's not the alphabet, there are missing letters.

good thing to add here is that the base58check reduces typing errors as the characters in the alphabet used to encode remove certain characters such as symbols as well as similar looking errors such as lI (lowercase "L", uppercase "I")

A Bitcoin address is a series of bits (on its simpler form is just a public key).
In order to make it human "readable" it is converted to a series of letters.
Base64 is a well known previous algorithm for doing this, but it was decided that characters as O, I, 1, l, +, / could lead to confusion (they are visually similar to others or aren't letters), so 6 out 64 chars were removed: from that the Base58 name.
Before doing the conversion, checksum bits are appended. This ensures that after conversion to Base58, any error transcribing a letter would lead to an invalid address when converted again to bits and the checksum is verified. From that the Check of Base58Check.
As Base58Check is just a representation of the original bits value, this latter bits serve also as an address (for example for backup purposes). It is more a matter of if the app you are using accepts bare bits as addresses.
npm bs58 just converts bits to Base58 without calculating nor verifying the checksum.
npm bs58check appends the checksum when converting bits, and verifies it when reverting from Base58 to bits.

Can someone explain what it is and why it's called Base58Check encoding?

Because of the name the function in the original Bitcoin codebase had.
The "Base58" refers to the fact that it is a base 58 format (it uses 58 different characters to encode the data), and the "Check" refers to the fact that a checksum is added to the encoded data.

Are addresses generated without going over those steps still valid in Bitcoin?

It's complicated.
Base58Check is simply a way to encode a number of bytes of data into a string. In theory, if you find another way to construct a string that can be decoded by the Base58Check decoder to something with the right length and version byte, the result will indeed be a valid address.
I expect the answer to your question is no. You need to use something at least vaguely similar to a Base58Check encoder to end up with a valid address.

To further this question, what do npm packages like bs58check do exactly?

It implements a way to convert bytes to Base58Check strings, and a way to convert such strings back to bytes.


text:
unable to read macaroon path (check the network setting!): admin.macaroon: no such file or directory on lncli getinfo
Just started lnd for the first time connected to a bitcoind node. Do lncli getinfo and this is the error message. How can I get past this?
EDIT: Would like to add that I'm using lnd on testnet, however lncli is looking in the mainnet folder

Found the issue, lncli needed to be set to testnet and you need to create a wallet as well
lncli --network=testnet create
lncli --network=testnet getinfo

The answer should be more general. try mentioning the fact that one needs to provide a proper --rpcserver and --macaroonpath to match both lnd and lncli. For example: if lnd was started with:
lnd --rpclisten=localhost:10003 --listen=localhost:10031 --restlisten=localhost:8003 --datadir=data
then lncli should be started with:
lncli --rpcserver=localhost:10003 --macaroonpath=data/chain/bitcoin/testnet/admin.macaroon
supposing lnd was to be used with the testnet flag. The flags network=testnet or -n testnet are just a particular scenario of this.

After installation of the lnd for the first time you should initialize a wallet with a command: lncli create
Here is description of startup commands:
lncli help
...
Startup:
create          Initialize a wallet when starting lnd for the first time.
unlock          Unlock an encrypted wallet at startup.
changepassword  Change an encrypted wallet's password at startup.

It may require you to create the path:
mkdir -p <path from error message>


text:
How to run bcoin on testnet?
In the documentation you can specify a network param, but the default main network name isn't the same as bitcoind (livenet). What is the name of testnet on bcoin?
EDIT: When going by the documentation and adding network: testnet to bcoin.conf, I get the error
AssertionError [ERR_ASSERTION]: Unknown network.
at Function.create (/usr/local/lib/node_modules/bcoin/lib/protocol/network.js:161:3)
at Function.get (/usr/local/lib/node_modules/bcoin/lib/protocol/network.js:207:20)
at FullNode.Node (/usr/local/lib/node_modules/bcoin/lib/node/node.js:43:26)
at new FullNode (/usr/local/lib/node_modules/bcoin/lib/node/fullnode.js:46:8)
at Object.<anonymous> (/usr/local/lib/node_modules/bcoin/bin/node:12:8)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)

My bcoin.conf file is
network: testnet
prefix: ~/.bcoin
prune: true
http-port: 8332
api-key: ******
uri: http://localhost

Are you referring to http://bcoin.io/ ??

Yep! And alternate to bitcoind

Just curious what is the advantage of bcoin to bitcoind?

Very modular, entirely written in node.js, has an extensive api built out so you can easily build on top of a node (previously only possible with bitcore), and has an active team whose focus seems to be making this more developer friendly. For example, I'm building a mobile wallet with bcoin as a local backend (without using the node functionality). You can't do that with bitcoind.

This might be as a result of a previous ChainDB having been initialized at ~/.bcoin/chain.ldb/ . You can find information inside of the debug.log file. e.g.
[I:2017-07-17T09:11:47Z] (chaindb) Opening ChainDB...
[E:2017-07-17T09:11:47Z] (node) Network mismatch for chain.

create a new location for the chain, e.g. ~/.bcoin/testnet/
copy the above config with the updated prefix as per the above
execute
bcoin --prefix ~/.bcoin/testnet/

Default prefix is "~/.bcoin/", you can override this by using the prefix cli flag

To add to this, you can specify a config file with bcoin --config=~/.bcoin/bcoin.conf (your config location) or you can set a different config file in the testnet or main folder and bcoin should pick it up

As stated by the configuration page, you set
network: testnet
In your bcoin.conf file.

See the question again, I updated it with an error related to this solution (provided by the documentation)

Did you add the network: testnet to your config file?

Yes, the error occurs when using that config file. The command I use to specify the conf file is bcoin -config=~/.bcoin/bcoin.conf


text:
How do zero-conf channels work?
What zero-conf channels are seems pretty straighforward (correct me if I'm wrong) -- channels that are immediately usable without needed confirmation on the blockchain. These are very useful since Alice can get Bob set up on Lightning without needed to wait for confirmation.
If there are different variants, can you describe how each works,trust assumptions, and possible drawbacks/attack vectors?

Just to expand a little bit the answer is already given.
Zero-conf channels, also called turbo channels, are new single-funded channels where the funder gives some or all of their initial funds to the acceptor. Those funds are not secure until the channel open transaction receives a sufficient number of confirmations, so there’s no risk to the acceptor spending some of those funds back through the funder using the standard LN protocol.
For example, Alice has several BTC in an account at Bob’s custodial exchange. Alice asks Bob to open a new channel paying her 1.0 BTC. Because Bob trusts himself not to double-spend the channel he just opened, he can allow Alice to send 0.1 BTC through his node to third-party Carol even before the channel open transaction has received a single confirmation.

See more here: https://bitcoinops.org/en/topics/zero-conf-channels/
See the BOLT RFC here: https://github.com/lightning/bolts/pull/910
ofcs you are trusting the other side so in case of fee spike there are problems

You can have a trustless zero-confirmation channel if it's funded from a 2-of-2 multisignature address and each party has one of the private keys. As far as I can tell, any other setup requires trusting the other party that they don't try to double-spend. Other than that, it works just like a normal channel.

Except this model is susceptible to fee based attacks like cpfp based tx pinning

Stumbled upon this question while searching something else. A wiser arshbot knows that cpfp carve out solves this concern.


text:
Checking balance on a block explorer
Very new to Bitcoin. Using Bluewallet. Wanting to verify my balance outside of using the wallet (say for paranoia/curiosity).
I copy my public key (using the "receive" button of Bluewallet to get said key).
I enter that address into block explorer type websites. It shows zero balance.
Is the address generated to receive coins not the right one to use for this purpose? I don't know how to view any other.

You surely thought about this, but worth noting explicitly: disclosing your public key / address does have privacy implications, even though it's fine from a security perspective.

Did you check Electrum wallet? It's easy to use and very powerful.

I don't know Bluewallet, but maybe this can help you, maybe not. Maybe that depends on the mix of on-chain vs lightning network transactions you have been using.

I copy my public key (using the "receive" button of bluewallet to get said key)
I enter that address into block explorer type websites. It shows zero balance.

When you tap "receive" on your phone, if it cares for privacy, it should give you a different and unused address each time.

Is the address generated to receive coins not the right one to use for this purpose?

That address would be the right one to use for that purpose, not before it has been given to some other person or system. In case it is a new address each time you tap.

I don't know how to view any other

You look for some panel of balance history, and look for past transactions' addresses, those used addresses would be what you should feed chain explorers when reading past transactions.

In addition to this answer if you want to verify the exact amount of your balance you should check all your sent transactions beside your received transactions.
Every transaction you create has probably some change. And that change goes to another newly generated address which is not very obvious at the first time.
The below picture demonstrates it clearly. Bob has a 50 BTC coin. He decides to send 0.5 BTC to Alice, so he construct a transaction which has one input (the 50 BTC coin) and two output, one with amount of 0.5 for Alice, and the other with the amount of 49.5 back to his wallet. But probably the 49.5 BTC is now went to a new address.

To read more about it take look at this article.
Source of image.


text:
Why bitcoin's generator point does not satisfy Elliptic Curve Cryptography equation?
This is my Python program:
Acurve = 0
Bcurve = 7
Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8

print(Gy**2 == Gx**3 + Bcurve)
print(Gy**2)
print(Gx**3 + Bcurve)

This is the output:
False
1067362225016502275772194909503713869376985974142797512091458491530306631211206623652669436957676354343630306950631573032330832513385319878364322508915776
166977061698153803977729810299616665720111080589888563362701662779994291659333477169534477572723704285154275133397811778652651956291844366636068483203593094558427352525126936769086968791554813695916119291254705683450242657305024007

Why is the equation not satisfied for the generator point?

The secp256k1 arithmetic is defined over the finite field of integers modulo 2256 - 232 - 977.
The following code works:
M = 2**256 - 2**32 - 977
Acurve = 0
Bcurve = 7
Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8

print((Gy**2 - Gx**3 - Bcurve) % M == 0)
print(Gy**2 % M)
print((Gx**3 + Bcurve) % M)

with output:
True
32748224938747404814623910738487752935528512903530129802856995983256684603122
32748224938747404814623910738487752935528512903530129802856995983256684603122


text:
Time delayed transactions as a solution for the inheritance problem?
Is it possible to construct a transaction which is delayed in time, more specifically blocks?
The idea being that you have a device which has a signed transaction, which sends all of your Bitcoin to the address of your kid once a certain block is reached.
Is this possible? Seems to me to be an easy solution to the problem of how to pass on your Bitcoin.

Yes there are timelock scripts (and opcodes) in Bitcoin.
From the Mastering the Lightning Network book (Antonopoulos, Osuntokun, Pickhardt):

Bitcoin has two levels of timelocks: transaction-level timelocks and output-level timelocks.
A transaction-level timelock is recorded in the transaction nLockTime field of the transaction and prevents the entire transaction from being accepted before the timelock has passed. Transaction-level timelocks are the most commonly used timelock mechanism in Bitcoin today.
An output-level timelock is created by a script operator. There are two types of output timelocks: absolute timelocks and relative timelocks.
Output-level absolute timelocks are implemented by the operator CHECKLOCKTIMEVERIFY, which is often shortened in conversation as CLTV. Absolute timelocks implement a time constraint with an absolute timestamp or blockheight, expressing the equivalent of "not spendable before block 800,000."
Output-level relative timelocks are implemented by the operator CHECKSEQUENCEVERIFY, often shortened in conversation as CSV. Relative timelocks implement a spending constraint that is relative to the confirmation of the transaction, expressing the equivalent of "can’t be spent until 1,024 blocks after confirmation."

Obviously your descendant would need access to the relevant private key (and no one else should be able to access it) for whenever the timelock expires but the timelock would prevent the spending of the Bitcoin until then. More complex arrangements (e.g. a combination of multisig and a timelock) may be superior to protect against the possibility of someone other than your descendant getting access to the private key.

Just to clarify: Would it be possible to have a transaction like this that does not actually specify the amount of Bitcoin that will be spent? The idea being that you can still use all of your Bitcoin as you please but after x amount of blocks all that remains is sent to another address, the owner of which (the descendant in this case) could also already create such a transaction for his descendants, without actually having received the Bitcoins?

No. If a timelock is imposed on particular UTXO(s) you need to decide which UTXO(s) have a timelock imposed on them and hence the amounts that have timelocks imposed on them. You can't impose a timelock on a fraction of a UTXO amount without splitting that UTXO into multiple UTXOs and imposing timelocks on only some of these UTXOs. Once a UTXO is spent it imposes no restrictions on future UTXOs created.


text:
How to develop a crypto exchange leveraging on third party API like coinbase, blockchain.com
I got a request as a developer to develop a bitcoin exchange site like https://mypatricia.co/ or https://instantcoins.ng/ I am to leverage on third party API like Coinbase, blockchain, it could be anything reliable API.
Users will be able to buy and sell bitcoin. For instance USER A makes an offer. USER B is interested in USER A's offer. When USER B clicks a button, with be a switch from USER A's wallet to USER B's wallet. Before the EXCHANGE is done. USER B is prompted to make payment in local currency.
I have been looking at https://developers.coinbase.com/api/v2#introduction https://api.blockchain.com/v3 I dont know how to go about it.
Is there any other better ones to work with?
There will be some other endpoints like
Where users get list of their orders
check wallet etc
I will appreciate your contribution

I think you are somewhat confused on what you want to build. You can either (try to) build an exchange that sources Bitcoin from an exchange like Coinbase or Blockchain and then sells them on for a markup. Or you can build a P2P exchange like Bisq, Paxful, LocalBitcoins etc. If you do the former it isn't P2P and it is subject to limits enforced by the API provider. If you do the latter you have no use for an API from Coinbase or Blockchain. Bisq is open source so you could look at their code if you want to understand how their P2P exchange works.


text:
When using bitcoin-cli I get an error regarding fallback fees when trying to send regtest Bitcoin. How do I resolve this?
I have been doing an assignment on Bitcoin Core 0.20. Now every time I try to do a transaction:
Apples-iMac:bitcoin apple$ bitcoin-cli -regtest sendtoaddress bcrt1qd3jck0lv87yuk25tk3xy5rqq67apwasee874xk 25
error code: -4
error message:
Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.

Can some one help me - what should I change? Please give a step by step guide as I am a complete newcomer.

bitcoind uses transactions it relays (and later see as mined) to estimate the feerate to set for transactions its wallet creates.
On regtest, you don't relay then mine enough transactions so bitcoind's estimation buckets are not filled enough to give a reliable estimate. Without such an estimate the wallet, out of safety, prefer not to create any transaction unless you explicitly tell it what fee to use when fee estimation isn't available.
This "fall back feerate" can be set up at bitcoind's startup with the fallbackfee startup option, expressed in BTC/kB.

   -fallbackfee=<amt>

         A fee rate (in BTC/kB) that will be used when fee estimation has
         insufficient data. 0 to entirely disable  the  fallbackfee  fea‐
         ture.  (default: 0.00)

Alternatively, crafting transactions on different nodes of your regtest network and getting them mined will result in estimation buckets to be filled.

You could enable -fallbackfee (as darosior says) but the easiest or quickest way to resolve this is to set a fee. In this example we are setting a fee of 1 satoshis per byte.
./bitcoin-cli sendtoaddress "bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hufdl" 0.1 "" "" false true 1 sat/B

If you do
./bitcoin-cli -regtest help sendtoaddress

you will see what those arguments after the regtest address represent.
Alternatively if you want to set the fallback fee see this StackExchange question.
This PR 16524 merged in October 2019 disabled -fallbackfee across all chains (mainnet, testnet, regtest) by default.

You can set the fee rate easily when using named parameters:
bitcoin-cli -regtest -named sendtoaddress \
  address=bcrt1qd3jck0lv87yuk25tk3xy5rqq67apwasee874xk \
  amount=25 \
  fee_rate=100


text:
When I try to download Bitcoin Core on MacOS it says "Apple cannot check it for malicious software"? Is it safe to download?
Brand new Mac Mini, latest macOS Catalina (10.15.6 (19G2021)), followed instructions on bitcoin.org download page.  Double click Bitcoin Core.app, and I get:

“Bitcoin Core.app” can’t be opened because Apple cannot check it for malicious software.
This software needs to be updated. Contact the developer for more information.

Any suggestions?

This error is due to macOS requiring apps to be "notarized" by Apple. Bitcoin Core doesn't do this (yet) for privacy reasons (it causes macOS to phone home to Apple servers). I'm not sure how to bypass this error, but Apple claims it can be ignored. So the solution will be a general "app notarization bypass" kind of thing that you can try to search for.

As mentioned by Andrew, this is due to macOS' enforcement of notarization requirements.
This can be bypassed by right clicking on the application, then selecting Open - A dialog will popup warning you that it is not verified, but this one will have an Open button.
Once you open the application through the above process once, a regular double click will work on it in the future.
You may need to go through this process again if you update to a newer version of Bitcoin Core.

Thanks both!  Yes, I googled around some more after posting, and found it, but thank you for getting back to me and confirming.

To add to Raghav's answer above, Cobra recently posted this question on Twitter with a screenshot of what you see when you download Bitcoin Core on MacOS for the first time.

He outlines what would need to be done for Bitcoin Core developers to address this:

The fix is trivial, just sign the application with an Apple developer account certificate, and notarize it, and it will run immediately for users, without showing this warning.

But Andrew Chow explained on Twitter why Bitcoin Core developers have not done this:

a notarized app will phone home to Apple's servers to verify that the notarization is valid. This privacy concern is what stopped the attempt to notarize Core, otherwise it would have been done a while ago. Many devs are not comfortable with that invasion of privacy.

Does a user trusting apple mean that they are opting into apple being the final arbiter of what they can run on their machine? Because AFAIU, that's what app notarization does. Apple can revoke notarizations thereby preventing an app from being installed.

Cobra argues that

Core makes requests to DNS seeds, which leaks the user's privacy to random Core developers, but somehow, the user shouldn't trust Apple, their own OS provider?

and

Apple's walled garden is a major selling point, many people like applications being vetted and pre-approved.

That summarizes the arguments for and against the Bitcoin Core developers addressing this user experience problem on MacOS. I would expect this to continue to be a user experience problem for the foreseeable future.

Andrew Chow himself reiterated his explanation with a comment to the original question :)

When you see that dialog,

Press Done
Open System Settings -> Privacy & Security
Scroll down and search for "Bitcoin Core" was blocked to protect your Mac
Press "Open Anyway" button, when a dialog is shown up, press "Open Anyway" button from the dialog. Then enter your mac's password.
Now try to open the app again.


text:
Can ASIC or FPGA boards be used to mine Litecoin?
I know that Litecoin was designed to be mined with a CPU but then someone figured out how to mine it with a GPU.
Has anyone figure out how to mine Litecoin with an ASIC or FPGA boards, and if not is it conceivably possible? (and by that I mean would it be more effective)

I found this discussion on bitcointalk very informative. Meni is correct but for those of you building rigs, I think FPGA/ASIC's for litecoin are still far off.

So say a 1TH/s Bitcoin miner attached to a PC with 128GB RAM and 2GB Graphics card could not run scrypt with any edge?

@user898617 Nope. The limiting factor to how fast you can mine is how many scrypts you can do, and Bitcoin mining ASICs don't do any scrypts.

Yes, there are designs for Litecoin mining FPGA bitstreams, but they are not very efficient currently. ASICs are much more efficient and if anyone finds it lucrative to invest in development of Litecoin mining ASICs, they will push out GPU mining. (The efficiency ratio between ASIC and GPU will be lower than with Bitcoin though).

What would an ASIC implementation look like for scrypt, technically speaking? My understanding is that the comparatively large memory requirement would need to somehow be addressed in an ASIC design.

@nitrl: I don't know all the technical details, but presumably the board that houses the ASIC chips will just also need to include a sufficient amount of RAM.

Litecoin uses scrypt instead of sha as its crypto function.
Scrypt is a memory hungry algo, so it's very difficult to have efficent implementation on ASIC or FPGA at current technology.
This choice was made to prevent ASIC and FPGA specialized mining in favour of more diffuse and generalized mining with standard hardware.
UPDATE
After just about 3 months my answer is old.
There are company working on ASIC chip for scrypt promising release during current year


text:
Official Canadian source saying bitcoin is not legal tender?
I've been reading a lot that Canada no longer considers bitcoin legal tender.

"Only Canadian bank notes and coins are recognized as legal tender in
  Canada. Bitcoin digital ‘currency’ is not legal tender in Canada,” an
  official from Canada’s finance department said in an emailed
  statement.

It can be read in all of these places:

Canada Real Time
Memeburn
The Wall Street Journal

among others. However, not a single one that I can find sites the source document. They all just seem to refer to each other. Does anyone have a copy of the email or government source document stating this? I'll also accept proof that the document never existed as a valid answer.

The perceived impact of this depends completely on how "legal tender" is defined. https://en.wikipedia.org/wiki/Legal_tender might be useful reading. Note the list of common payment instruments which are not usually considered legal tender.

The country has come out and said that they don't consider bitcoin legal tender. I'm looking for the source document that actually says that.

Your "no longer" is misleading. As Greg's answer suggests, Bitcoin was never legal tender. Note that does not mean that it's illegal to use! "Legal tender" has a very specific meaning. What this means is that, for instance, if you owe somebody money and offer to pay them in Bitcoin, they can refuse it and sue you instead. The same is true if you offer to pay them by check, credit card, or in gold; those are not legal tender either.

The Currency Act defines what is meant by legal tender in Canada:

Legal tender

8. (1) Subject to this section, a tender of payment of money is a legal tender if it is made
(a) in coins that are current under section 7; and
(b) in notes issued by the Bank of Canada pursuant to the Bank of Canada Act intended for
circulation in Canada.

Since these are the only two forms of payment considered legal tender, and bitcoins are quite clearly neither of these, the conclusion must be that bitcoins are not legal tender in Canada. Note that the Act doesn't explicitly have to name Bitcoin for this conclusion to nevertheless be true.


text:
How to recover forgot about Bitcoins
I do not remember the details but I got some Bitcoins for free years ago. I think it was on a slot but can not be sure.  How can I go about trying to find out where I would have put them if I even kept them at all. I might even have lost them right back to the slot if that is where I got them. I just remember getting them at a time I never had heard of them. Just a thought.  why not find them if I can.

If you withdrew the BTC then you must have had a wallet somewhere to withdraw to. A wallet software could have been installed on your PC or, could be with a web wallet provider or, the balance could still be with your slots.
If you have no information about your wallet (check old emails for account information from a web wallet provider), cannot remember any details and, cannot find any evidence of any Bitcoin wallet on your PC (there are may but, they all make a data folder somewhere..) then, unfortunately, your BTC is lost.


text:
How to set up a private chain/local testnet : reverse engineering the blockchain code
Long story short, I want to set up a private chain/a testnet blockchain that can run locally just to fiddle and play with it just to learn how it works. So I have a general understanding of how things work and thought that to really learn I would need to reverse engineer and play with it as much as I can.
So, how would I go about that?
What I am looking for is ideally a step by step clear, beginner friendly explanation because I am aiming at blockchains written in javascript (lisk, nimiq) or, in python(bismuth)
Let me first tell you what I thought of or, what I think concerning ways to do that. I imagine I would have to:

Decide which existing blockchain would resemble the most with what I have in mind regarding the consensus algorithm
Download it from GitHub
Establish a dev environment
Run different tests and let my brain do its magic

Now with regards to those steps, I have few questions:

Am I missing something like an intermediary step let’s say?
Regarding step 1 where should I look, what parts of a blockchain will be the deciding factors for me choosing one over the other say considering that I want to introduce a new consensus algorithm?
Regarding step 2, how would I download a blockchain but ignore the transaction history (this will be a new altcoin starting with genesis block) or is that more like something I change within the code not sure?
Regarding step 3, this is where I would appreciate a step by step response since I have no idea what to download and what steps to take to get from: "I have the code" stage to "I can play with it and test different things" stage.
Regarding step 4: except deleting part of the code, changing variables value, switch order or lines what else could help me to understand better how the code works?

Thank you

Related: https://bitcoin.stackexchange.com/questions/14187/when-making-an-altcoin-copy-of-bitcoin-where-should-one-start

Related: https://bitcoin.stackexchange.com/questions/28212/where-do-i-start-for-creating-altcoin

Welcome to Bitcoin.SE! You plan to establish a development environment, on what platform?

The question slightly exceeds capabilities of this q&a forum. Maybe better to search bitcointalk.org, there these type of requests get often discussed. Join one of the discussions there!
Anyhow, we need developers, and people with fresh minds.
Here my short shot at bitcoin, because we are in bitcoin q&a forum. You would probably want to create an altcoin of it. For sure the relevant info and link to the code is on bitcoin.org.
To accomplish your goals, you would have to have an idea and sometimes excessive knowledge on the following:
Information Security
Overview of current crypto coin technologies
Finite Fields
Elliptic Curves
Elliptic Curve Cryptography
Signing/Verifying Messages
Parsing Transactions
Signing Transactions
Creating Transactions
Script parsing and processing
Address construction/Private Key WIF Format Construction
Extended Keys (XPriv and XPub)
Parsing Blocks
Validating Proof-of-Work
Difficulty Calculations
Merkle Tree Construction
Merkle Proofs
Network Message Parsing

and maybe
Segwit
Lightning
Altcoin
...

The list can be for sure extended :-) So you choose to go for a steep learning curve. From what I read in your message, I think you are not (yet) there, but that's not an issue. You will probably want to read books like Andreas' "Mastering Bitcoin", and some more. They will bring you up to speed.
If you think of on the environments (like Ethereum or IOTA), I doubt that many devs are here to support.

1) decide which existing blockchain would resemble the most with what
  i have in mind in terms of consensus algorithm

this is s.th. we can't help you with, as you haven't presented anything. Do you want to use the community's power & efforts to bring your project forward, but don't provide input to the community by hiding your logic and ideas? In general: we are very curious here for new ideas :-)

2) download if from github

see the links on bitcoin.org

3) establish a dev environment

You take a linux machine, and install the software, compile it, and see how you go. Alternativly you can try your luck in other OS, but support is way better on unixoide systems. Also the usage of virtual machines is very attractive.

4) run different tests and let my brain do it’s magic

again, this is up to your mind howto. But there are testcases deliverd with the software, so you can find relevant code for it, adopt it to your requirements, and go.


text:
Android on Copay still available?
Hi I was downloading Copay and it said ;

WARNING: Chrome App will not longer be supported
Google has announced that it will be ending support for Chrome Apps on non-Chrome OS platforms in 2018. This means that our Copay bitcoin wallet will no longer be available. Please use other Copay platform. If you are using a hardware wallet, we recommend that you move your funds to other wallet as soon as possible.

I was wondering if it is okay to download from google store and use or if I should just use the wallet on another platform?

Android apps are unaffected by this change.


text:
Any attack vector for Proof of Witness?
When Alice wants to send Bob some coins all she has to do is sign a transfer of ownership with her private keys and publicize that announcement until Bob is happy with the number of witnesses. For small transactions, Bob might be happy with a couple dozen witnesses but with large value transactions he'd want thousands of heavy peers to witnesses the transaction. Why?
Bob's coins only belong to him if someone on the network can provide proof to everyone else, on demand, that those coins belong to Bob. If all of Bob's witnesses go offline then there's no one to vouch for him! In such a scenario, Alice would be able to transfer the ownership of those coins again since no one would be there to stop her.
This is basically turning the current popular algorithms upside down since you're not flooding the network with transaction data, you're listening to the network to make sure no one is trying to take your coins. As long as you yourself are online ready to provide proof, the transfer of ownership signed by Alice, then no one can take your coins away from you. Ideally, you'd have many peers ready to provide that proof, not just you in case you go offline and in exchange you either pay them a small fee or you also host others' proofs ready to serve them up to whomever asks for it.
The only attack I can think of is Alice announces the transfer of ownership of coins to Bob and announces another transfer of ownership of the same coins to Mallory at the same time and hopes that Bob and Mallory don't hear each other. But if Bob and Mallory are smart they'll query enough peers such that their queries overlap and collide in at least one peer on the network.
So to wrap up: using witnesses to 'hear' the transfer of ownership and at least one of those witnesses ready to defend the transfer of ownership is enough to prevent double spends. Caveats are that you want enough witnesses to hear the transfer and you want at least one witness always online. In bitcoin, your funds are safe even if go offline but here your funds are only safe if you're online 24/7. Otherwise you need to trust 3rd parties to defend your coins for you. Are there any attack vectors with this? It sounds pretty simple, too good to be true? Consensus is too slow and we don't need consensus here. And you don't need synchronization since everything would be dynamic.

Can this Proof of Witness be attacked in a way I'm not seeing?

Is that a Question?

Yes, I asked if this can be attacked in a way I'm not seeing.

You could be sybil attacked. There is very little cost to witnessing a transaction so an attacker could spin up many nodes that claim to have witnessed a transaction that double spends another transaction. Proof of Work is secure because it requires miners to spend money to incorporate transactions in the blockchain and any attacker has to spend money too. In fact to change a transaction you have to change the block it was incorporated in and all subsequent blocks. It quickly becomes infeasible to do so.

Thereare many assumptions in your post, which leads to a wrong understanding of how bitcoin works. I recommend to read the book of Andreas („Mastering Bitcoin“), and here the introduction chapter and the transaction chapter.
Bitcoin is a public ledger, and the ground rule is, that you wait for a confirmation, to be sure you’re funds are transferred. At this point in time the network will reject any double spends. Using bitcoin in the way you described, would mean having trust in a person (and not a confirmed transaction), and this can of course be misused.
For large transfers it is repeated over and over again, that 6 confirmations (not thousands, that is a wrong understanding of the system) should be waited (approx. 1hour), before your funds are „safe“.

Bob's coins only belong to him if someone on the network can provide
  proof to everyone else, on demand, that those coins belong to Bob.

No... The coins belong to Bob, once Alice has sent the coins, and the network has verified the transaction and included in a block (aka 1st confirmation). Understand that are no person, people or witnesses involved. It is the math in the applications, which does the confirmation. So the blockchain is the proof, that funds belong to Bob.

Alice would be able to transfer the ownership of those coins again
  since no one would be there to stop her

No, when Alice wants to send another transaction into the network, the receiving node would verify the contents, and reject it, cause it is a double spend.

In bitcoin, your funds are safe even if go offline but here your funds
  are only safe if you're online 24/7.

No... it doesn’t matter if you are online or not. At the point the tx is confirmed, the funds are „yours“ - completely independent if you are on or not. It is not about people being on, who do the verification. It is the apps.  Again, please have a look at the book, this helps to overcome the wrong assumptions. The book is available online.

I wasn't describing bitcoin's consensus algorithm. I was talking about a different algorithm that is going to be used for an upcoming coin. I want to know if this algorithm makes sense.

The reason I'm asking is because it seems like an obvious algorithm to use. If Alice wants to spend her coins again you just need to show up and say no look i have the certificate of ownership now. So there's no ledger anymore there's only a list of who owns what coins.

Ah, ok, this is a bitcoin forum, hence my replies are relevant for bitcoin. Maybe you should mention this in the beginning of your question...


text:
How strict are the Unix Epoch time validation rules?
According to bitcoin.org, full nodes have a strict requirement on the deviation of time within certain boundaries.

The block time is a Unix epoch time when the miner started hashing the header (according to the miner). Must be strictly greater than the median time of the previous 11 blocks. Full nodes will not accept blocks with headers more than two hours in the future according to their clock.

However, if given a certain circumstance, it appears the blockchain is at risk of rejecting all blocks due to conflicting validation parameters.
For example, in the instance of a severe difficulty drop. Difficulty in bitcoin is revaluated every
2016 blocks. If the difficulty drops drastically enough, it could be hours or days until the next valid block is found since the network is operating with reduced mining capacity at a difficulty level intended for much greater. If the next block is mined more than two hours after the current block, would this not stall the blockchain? What would happen in this given scenario?
How strict are the time validation rules?

How strict are the time validation rules?

Very.

If the next block is mined more than 2 hours after the current block, would this not stall the blockchain?

No.
It doesn't break the rule "Full nodes will not accept blocks with headers more than two hours in the future according to their clock."
Nor does it break the rule "Must be strictly greater than the median time of the previous 11 blocks."

The above should be clear I hope, but in case it isn't, lets make an example:

Event
Time

Last block mined
08:00

Median time of last 11 blocks
07:00

Current time on my clock
11:00

Time on block arriving now
12:59

Rule
Result

(12:59 - 11:00) < 2
OK

12:59 > 07:00
OK

So no problem even though there's been a three hour gap instead of 10 minutes and even though the block has a timestamp that I think is nearly two hours in the future!
Note that these particular rules are not broken if there is a huge (e.g. 50 year) gap between blocks. In theory everything would continue (though it seems likely there would be other issues preventing this)

Fair enough, miners aren't restricted to putting in a certain time

@arshbot That's true, but not relevant I think. Even if the timestamps in blocks are always exactly equal to the time the block is produced, there is no problem.

I think you have a misconception about what this clause means:

Full nodes will not accept blocks with headers more than two hours in the future according to their clock.

You appear to be interpreting this as, if a new block is more than two hours later than the previous block, then do not accept it. That is incorrect. This clause is not about gaps in time between blocks.
The actual meaning of this clause is that, if a new block says it's literally from the future, from a time that the universe has not yet reached, then do not accept it. This clause is about preventing manipulation of the blockchain via falsified timestamps.
This comparison is between the new block's timestamp and your clock, not the new block's timestamp and the previous block's timestamp.


text:
bitcoinjs-lib seems to skip a step in deriving addresses from a BIP 44 wallet
According to this wiki page to create a bitcoin address,
1) you have your public key of the properly derived path
2) Then SHA256 it
3) Then RIPEMD-160 it,
Add version byte at the front and boom blam you’re good.
But in bitcoinjs-lib, they have this function getAddress which seems to skip step 2  and continue down the path ensuring Base58Checking
function getAddress (node) {
  return baddress.toBase58Check(bcrypto.hash160(node.publicKey), bitcoin.networks.bitcoin.pubKeyHash)
}

My question is, why is bitcoinjs-lib skipping step 1? Don’t you have to SHA256 the pub key again?
Derivation occurs pretty straightforwardly with derivePath
var child1 = root.derivePath("m/44'/0'/0'/0/0")

https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/src/crypto.js hash160(buffer) is ripemd160(sha256(buffer))

Yes, that is obvious. The step skipped is the extra SHA256

Ah I see, my bad. Leave a proper answer so I can give you credit


text:
How to generate a dash address?
How can I generate a simple dash address from a public key?
How many address formats are there in dash?

How many address formats are there in dash?

Dash seems to be pretty similar to bitcoin when it comes to address and transaction formats. You have your typical P2PK, P2PKH, P2SH.
Here is how to generate a standard P2PKH address (and therefore also a P2PK address).
var bip39 = require('bip39');
var hdkey = require('hdkey');
var createHash = require('create-hash');
var bs58check = require('bs58check');

//const mnemonic = bip39.generateMnemonic(); //generates string
const mnemonic = 'thunder purchase pave tower lecture upgrade supreme half kid fitness tray shove'
const seed = bip39.mnemonicToSeedSync(mnemonic); //creates seed buffer
console.log('mnemonic: ' + mnemonic);

const root = hdkey.fromMasterSeed(seed);
const masterPrivateKey = root.privateKey.toString('hex');
//console.log('extended public key root:  ' + root.publicExtendedKey)

const addrnode = root.derive("m/44'/5'/0'/0/0");
console.log('addrnodePublicKey: '+ addrnode._publicKey.toString('hex'))
console.log('addernodePrivateKey: ' + addrnode._privateKey.toString('hex'))

const step1 = addrnode._publicKey;
const step2 = createHash('sha256').update(step1).digest();
const step3 = createHash('rmd160').update(step2).digest();

var step4 = Buffer.allocUnsafe(21);
step4.writeUInt8(0x4c, 0);
step3.copy(step4, 1); //step4 now holds the extended RIPMD-160 result
const step9 = bs58check.encode(step4);
console.log('\n\n\nmnemonic: ',mnemonic,  '\npath: ', path, '\naddernodePrivateKey: ' , addrnode._privateKey.toString('hex'), '\naddrnodePublicKey: ', addrnode._publicKey.toString('hex'), '\nBase58Check: ' + step9);

Notice the only difference between this and deriving a bitcoin address is the version bytes is not 0x00 but instead 0x4c & the derivation path coin index of 5 instead of 0.

Let's assume the private key is one of the worst low entropy private keys for demonstrative purposes is 0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff.
1. Dash P2PKH Address Calculation:
% echo 0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff | bx ec-to-public | bx ec-to-address -v 76
XyHHinPZB5Q4FC9jtbksaQBJmXq48gtVGb
2. Dash Single Signature P2SH Address Calculation:
% echo 0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff | bx ec-to-public
020d47568a5e517067a2836c3823fbc58169a7662bfae934a4d41da3e23c98d816
% echo "[020d47568a5e517067a2836c3823fbc58169a7662bfae934a4d41da3e23c98d816] checksig" | bx script-to-address -v 16
7fePc8Mf7RYghdxkSp5yaWfT9WR4F2Dsqa
Wonder where the 76 and 16 version numbers came from?
See the Dash row within  https://github.com/libbitcoin/libbitcoin-system/wiki/Altcoin-Version-Mappings#bip44-altcoin-version-mapping-table.


text:
How to identify P2TR output type?
The scriptpubkey alone can be used to identify the type of address. However, I'm debugging a library that's having difficulty differentiating the following transaction/scriptpubkey from a p2tr transaction/scriptpubkey.
Erroneously marked p2tr:
Txid: 2b3733a39b87cef1f7c2ca8988583ec0c1a886651b040e3dbaf4c26be81d0f75:195
Scriptpubkey: 245a227ef640f3b1dc1815e6e39b482677f0f57b69de7775faec778c0950a8851805000000
Correctly marked p2tr:
Txid: 83c8e0289fecf93b5a284705396f5a652d9886cbd26236b0d647655ad8a37d82:0
Scriptpubkey: 5120a457d0c0399b499ed2df571d612ba549ae7f199387edceac175999210f6aa39d
And honestly.. I understand why the library is having issues. The problematic scriptpubkey does look like a p2tr (1, data). However one thing I noticed is the problematic tx doesn't have witness (predates segwit). Is the only solution to check witness stack for the right pattern?

A witness stack is part of an input’s data. If you are trying to identify an output, how does the witness stack come into play? Are you trying to figure out whether an input is spending a P2TR output?

I don't see why that scriptPubKey would be incorrectly marked as P2TR as it absolutely does not follow the expected pattern. BIP 341 is very unambiguous as to the script construction - it must be OP_1 followed by a push of exactly 32 bytes.
The erroneously marked P2TR script is only a push of 36 bytes. It does not begin with OP_1, and the length of the data push is incorrect.

Is the only solution to check witness stack for the right pattern?

No. A transaction can consist of entirely non-segwit inputs and still create P2TR outputs. Such a transaction would not have any witness data.


text:
If hashrate falls for other main chains, will we be brave enough to enforce higher fees?
If in low inflation future users refuse to voluntarily pay high fees and reward is too low and for some reason network computing power (A.K.A. hash rate) falls, can we then expect consensus would try to soft fork higher minimum fees?

Scenario:

Time: Undefined future (low inflation future).

Consequence 1: Reward is low.

Proposition 2: Users won't voluntarily pay high fees.
Proposition 3: Price will stabilize eventually.
Proposition 4: Because (1), (2) and (3) the network computing power will fall.

Consequence 5: Alternative chains gain relative network power compared to Bitcoin.

Proposition 6: In an attempt to stop (5) bleeding, Core would try to soft fork higher minimum fees.

related: https://bitcoin.stackexchange.com/q/3111/5406

What does failure in this way actually look like? I don't think falling hashrate is it, more likely it is an extremely unstable chain-tip / ongoing majority attacks.

@chytrik I'm not sure I understand, but I would be keen to chat about it. :)

@Mercedes this site has a chatroom here if you'd like: https://chat.stackexchange.com/rooms/8089/mempool


text:
How to check whether a hex string is a key or an address and how to import it?
So after long digging I finally found my private key which is in hex format. When I paste it in one website it does validate the address, it is a legacy address, it is in hex format, but it's 66 characters long, I know privkey is 64 long, but when I uncompress it like I thought it may be just the public key, it shows different address I mean nothing close to mine? I'm confused literally, also what am I doing wrong, is this really the privkey, and if it is how can I import it?

is this really the [private] key [...]

According to Mastering Bitcoin, 2nd Edition by Andreas M. Antonopoulos, 66 characters is a possible compressed key in hex
and

This compressed public key corresponds to the same private key, meaning it is generated from the same private key. However, it looks different from the uncompressed public key. More importantly, if we convert this compressed public key to a bitcoin address using the double-hash function (RIPEMD160(SHA256(K))) it will produce a different bitcoin address. This can be confusing, because it means that a single private key can produce a public key expressed in two different formats (compressed and uncompressed) that produce two different bitcoin addresses. However, the private key is identical for both bitcoin addresses.

(my emphasis)
Antonopulos also gives an example of a compressed private key that I count as 66 characters long.

I would also check the format of your string against the examples in answers to how does the blockchain addresses relate to the blockchain WIF?
I strongly suggest no one ever puts a possible private key into any web-site. To me that is less safe than giving your physical wallet and bank login details to a passing stranger at a train station and asking them to come back next week and tell you if the contents are valid.

[...] and if [it is, how can I] import it?

See How do I import a private key into Bitcoin-Core? but remember, with many wallets you have to make a separate backup of the private key because imported keys are not recovered when using the recovery phrase. I think with Bitcoin core it may be enough to use it's "backup wallet" option and keep fresh copies of the backup on several different devices in different buildings. It is a good idea to test recovery from offsite backups before assuming your money is safe.


text:
Validate raw transaction hex without broadcasting
I would like to check the validity of a raw transaction (i.e. whether it would be accepted by network nodes), without broadcasting the transaction to the network. I am interested in knowing what is the best way to achieve this 1) using Bitcoin Core's RPC API 2) by any other means (e.g. open source tool).
Am I correct in stating that the sendrawtransaction RPC method first validates a transaction before attempting to broadcast the transaction to the network?
Edit - I'm aware that the decoderawtransaction method can be used to manually/visually assess the details of a transaction, but I'd like to be 100% sure that the transaction signatures and parameters are correct without having to actually broadcast the transaction.

The RPC you're looking for is testmempoolaccept. It checks whether a raw transaction would be accepted into the local mempool, without actually doing so. Only transactions that satisfy all consensus rules, plus various policy rules, are accepted into the mempool.

Am I correct in stating that the sendrawtransaction RPC method first validates a transaction before attempting to broadcast the transaction to the network.

Yes, broadcasting invalid transactions would be simultaneously bad for privacy, and risk being banned by your peer nodes.

Thanks for taking the time to respond with such a helpful answer, and so quickly, Pieter. You're absolutely indispensable.

What is the rationale behind naming the method testmempoolaccept? I immediately searched for a validaterawtransaction method in the RPC docs, then since there was none, I did a cmd+f for validate which obviously didn't help either. It seems more intuitive for it to be named validaterawtransaction/validatetransaction though I appreciate testmempoolaccept is slightly more descriptive.

I was doing the same thing as @satirn, I thought validaterawtransaction was a more intuitive name also.

I'm assuming testmempoolaccept also considers whether the spending inputs is in the valid utxo set. If so is there a way to also exclude that check in testmempoolaccept or some other command? For example, you want to check if a pre-signed transaction is valid but the input funds being spent haven't been committed yet.


text:
DLC funding transaction error: non-mandatory-script-verify-flag (Witness program hash mismatch) (code 64)
I'm attempting to construct a funding transaction for a DLC. So far I have created the following transaction which encodes entry of a bet for local/remote collateral of 1000/1000 sats and binary win/lose all or nothing outcome.
As far as I can tell, the transactions are accurate in terms of inputs/outputs addresses etc, and the signatures were provided (see below), but I'm getting this error:
non-mandatory-script-verify-flag (Witness program hash mismatch) (code 64)
when attempting to broadcast the transaction.
hex:
<txhash>

I also attempted broadcasting with another service, which had a more descriptive error so I'll also post this here:
Error validating transaction: Error running script for input 0 referencing <hash> at 1: incorrect number of witness items for version 0 witness program of length 20.
I'm not really sure how to interpret this error and also unsure of how to go about debugging, so any pointers would be really appreciated.
Searching for these errors on StackExchange doesn't seem to provide any relevant hits except maybe this answer. Is it possible that incorrect private keys used to sign the transactions could lead to the witness program hash mismatch? (as suggested by Andrew Chow).
{
    "addresses": [
        "<addrs>",
        "<addrs>",
        "<addrs>",
        "<addrs>",
        "<addrs>"
    ],
    "block_height": -1,
    "block_index": -1,
    "confirmations": 0,
    "double_spend": false,
    "fees": <amt>,
    "hash": "d6c6069357ed571c91294d736f44db57a22b1e422ebd6947cc912ef8f498f8ca",
    "inputs": [
        {
            "addresses": [
                "<addrs>"
            ],
            "age": 00,
            "output_index": 1,
            "output_value":<amt>,
            "prev_hash": "<hash>",
            "script_type": "pay-to-witness-pubkey-hash",
            "sequence": 4294967295
        },
        {
            "addresses": [
                "<addrs>"
            ],
            "age": 00,
            "output_index": 1,
            "output_value": <amt>,
            "prev_hash": "f174bf45da30a7a43360c37fde80955ad3e0b45e6913b0aab1314fdfabe2e0c7",
            "script_type": "pay-to-witness-pubkey-hash",
            "sequence": 4294967295,
            "witness": [
                "304402207bb9cffa80ee109758b6c0c74ac2d5745cb42bb06c76b0cf7a86e64cc4159bba0220351f1ae477c5703c2990336a2888a4ff1c52e3d01897931ba3b48fce694797c101",
                "022b89efbabb2ab7f712912c399ef161216b07d101fa95a3ffbb4ce675548b64e1"
            ]
        }
    ],
    "outputs": [
        {
            "addresses": [
                "<addrs>"
            ],
            "script": "002002349639c02aee43f4474e269bc03860d0290f7f3fc15f0bcea54b2025dffae8",
            "script_type": "pay-to-witness-script-hash",
            "value": <amt>
        },
        {
            "addresses": [
                "<addrs>"
            ],
            "script": "00147bd21f276fa2e6a81a69a1d89c4217876810bf98",
            "script_type": "pay-to-witness-pubkey-hash",
            "value": <amt>
        },
        {
            "addresses": [
                "<addrs>"
            ],
            "script": "00148e0892c30b293a2ae1fa90988cc6004f03eadc1c",
            "script_type": "pay-to-witness-pubkey-hash",
            "value": <amt>
        }
    ],
    "preference": "low",
    "received": "<datetime>",
    "relayed_by": "<ip>",
    "size": <size>,
    "total": <amt>,
    "ver": 2,
    "vin_sz": 2,
    "vout_sz": 3,
    "vsize": <vsize>
}

If you look at input 0, it doesn't contain a witness element, this means it isn't signed. You need to sign both inputs to be able to broadcast.

Thanks Ben, had missed that. Appreciate it


text:
Meaning of "Drop the signature" comments in OP_CHECKSIG code (Bitcoin v0.1.0)
I'm doing my homework by reading the C++ code of the 0.1.0 release of Bitcoin available here. I'm interested in better understanding how to validate transaction 1 of block 170. This transaction has one input, that points to output 0 of transaction 0 of block 9.
script.cpp contains a function EvalScript(). This function is called to execute the following script:
---- Bloc 170 / Transaction 1 / Input 0 / ScriptSig -----
PUSH 304402204e45e16932b8af514961a1d3a1a25fdf3f4f7732e9d624c6c61548ab5fb8cd410220181522ec8eca07de4860a4acdd12909d831cc56cbbac4622082221a8768d1d0901
---- Separator -----
OP_CODESEPARATOR
---- Bloc 9 / Transaction 0 / Output 0 / ScriptPubKey -----
PUSH 0411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3
OP_CHECKSIG

I had a look at the code for OP_CHECKSIG. This code creates a script that is going to replace the one that lies in ScriptSign of input 0 of a copy of transaction 1 of block 170 later in another function SignatureHash(). The first steps are pretty straightforward:
valtype& vchSig    = stacktop(-2);
valtype& vchPubKey = stacktop(-1);

This puts the signature (DER format) followed by the hashtype (0x01, so SIGHASH_ALL) in vchSig, and the public key prefixed with compression flag (0x04, so no compression) in vchPubKey.
CScript scriptCode(pbegincodehash, pend);

This creates a script that is nothing more than ScriptPubKey of Block 9 / Transaction 0 / Output 0.
And then...:
// Drop the signature, since there's no way for a signature to sign itself
scriptCode.FindAndDelete(CScript(vchSig));

I don't understand this. How could the signature that lies in ScriptSig of input 0 of transaction 1 of block 170 be found in ScriptPubKey of output 0 of transaction 0 of block 9, a previous block?
Of course, I know that this very transaction is a very basic one considering how complex a Bitcoin transaction can be, as explained by Satoshi himself here. But what would be a transaction where this code would be useful?

You are correct that the signature would not actually be present in that hash due to the OP_CODESEPARATOR used. Keep in mind that v0.1.0 was very unpolished code and had a lot of bugs and weird behaviour. Not everything makes sense.
To explain for those that want more context, by the time we reach EvalScript(), the script will be of the form:
txin.scriptSig + OP_CODESEPARATOR + txout.scriptPubKey

where txin.scriptSig is from the spending transaction input, and will contain the signature, and txout.scriptPubKey is from the previous transaction UTXO being spent and will contain the public key and OP_CHECKSIG opcode. This is exactly what is written in the question.
Starting from the beginning, the signature will be pushed onto the evaluation stack, then we will hit the OP_CODESEPARATOR so pbegincodehash will be updated to that point in the script, then the public key will be pushed onto the evaluation stack, and finally the OP_CHECKSIG is reached.
Exactly as you say, the signature and public key will then be taken off the stack in reverse order and stored in vchSig and vchPubKey respectively.
scriptCode is then set to the subscript starting at pbegincodehash until the end of the script. In this case, it starts at the OP_CHECKSIG we encountered previously, so scriptCode will simply contain the public key push and the OP_CHECKSIG opcode.
Thus, when scriptCode.FindAndDelete(CScript(vchSig)) is called, it does nothing in this case because vchSig is not part of scriptCode.
However, for the context of why deleting the signature from the script is important for verifying the signatures, let's look a bit further. CheckSig() is called with the signature (vchSig), the public key (vchPubKey), and the scriptCode:
CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType)

which then calls
SignatureHash(scriptCode, txTo, nIn, nHashType)

to generate the hash of the message. The hash is generated by deleting all remaining OP_CODESEPARATORs from the script, setting the scriptSig of all the other inputs to the spending transaction to empty, sets the scriptSig of the current input being signed to scriptCode, and then (ignoring the other signing types) serialises the transaction and hashes it.
Recall that to verify a signature we need the message (which is then hashed), the public key, and the signature itself. The message has to be in exactly the same form as what was originally signed. That is why we have to delete the signature itself from the transaction being signed, because it obviously couldn't have been present at sign time. However, in this case, it does nothing, because there are no signatures after OP_CODESEPARATOR anyway. The clearing of scriptSigs in the SignatureHash() function is more important here because they would all be empty at signing time.
To check this, we can take a look at the SignSignature() function too, which actually generates the signatures. We can see that it passes scriptPrereq + txout.scriptPubKey to the SignatureHash() function above as the scriptCode. scriptPrereq is always empty in this code. So basically scriptCode is always just the scriptPubKey. That matches exactly what we expect.

There are some exotic scriptSigs which contain additional OP_CODESEPARATORs and could have a signature, pubkey, and OP_CHECKSIG that all occur after an OP_CODESEPARATOR, and before another one. In that case, FindAndDelete would be doing something in order to remove the signature from the script. IIRC the TumbleBit protocol uses a construction like this.


text:
Conditional MULTISIG transaction
I need a bitcoin lock script that will require my key and 1 of 4 other people.
For example, If my key is present and one of the 4 other keys are also present, transaction can be claimed. If my key is not present, even the presence of all of the other 4 keys will not be enough to claim the transaction.
I have created a script like below but I couldnt figure out how to convert it to a lock script.
my_key OP_CHECKSIGVERIFY OP_1 key1 key2 key3 key4 OP_4 OP_CHECKMULTISIGVERIFY

The most straightforward (and safe) way is to use a Miniscript output descriptor. You can generate one using a Miniscript policy compiler.
For instance with your key A, and 4 other keys B C D and E the Miniscript policy could be and(pk(A),thresh(1,pk(B),pk(C),pk(D),pk(E))).
Using @sipa's online Miniscript policy compiler, this compiles to and_v(v:pk(A),c:or_i(pk_k(B),or_i(pk_h(C),or_i(pk_h(D),pk_h(E))))). You can then use the wsh(and_v(v:pk(A),c:or_i(pk_k(B),or_i(pk_h(C),or_i(pk_h(D),pk_h(E)))))) output descriptor in a wallet that supports it (for instance Bitcoin Core), to receive and send funds using this policy.

For what it's worth, the Bitcoin Script corresponding to the above Miniscript is:
<A> OP_CHECKSIGVERIFY OP_IF
  <B>
OP_ELSE
  OP_IF
    OP_DUP OP_HASH160 <HASH160(C)> OP_EQUALVERIFY
  OP_ELSE
    OP_IF
      OP_DUP OP_HASH160 <HASH160(D)> OP_EQUALVERIFY
    OP_ELSE
      OP_DUP OP_HASH160 <HASH160(E)> OP_EQUALVERIFY
    OP_ENDIF
  OP_ENDIF
OP_ENDIF
OP_CHECKSIG

Ha beat me to it. Deleting my answer :)

You just have to modify your script a little like that <my_key> OP_CHECKSIG OP_IFDUP OP_NOTIF OP_1 <key1> <key2> <key3> <key4> OP_4 OP_CHECKMULTISIG OP_ENDIF
It will require two signatures to unlock the transaction output, one from your key and one from the other four key.
To use this as a Bitcoin lock script you will have to create a P2SH address that will contain the hash of your script, also notice that this script is pre Taproot since it use CHECKMULTISIG(VERIFY) . And of course dont forget to test heavily all this on a testnet if you want to use real fund for it.

Thanks, but how do you make sure that my key is always present? As far as i understand, with your script, any combination of 5 keys can claim this transaction.

I think the question asker wants their key to be used for all spends with an additional key from the 4. Your script would allow spends without the question asker's key

I modified my answer, now it ensure that your key have to be present

Perhaps also state that this is pre Taproot and that with Taproot you'd use CHECKSIGADD rather than CHECKMULTISIG(VERIFY) that was disabled for Taproot addresses


text:
How to generate a lightning invoice of any type offline
Is it possible to generate a lightning network invoice without the encumbrance of a full lightning node (lightning node defined as: fully synced channel graph, knowledge of channel outpoints, and current channel state)?
How about bolt11, bolt12, amp invoices? Any other methods?

I think Bolt 12 or key send payments is what u looking for you can pay with ones node id. The receiver has yo obtain a node and also be online.


text:
How to get balance history of a bitcoin address using BCOIN node
Is there any way to get history balance of an address. Balance is unspent transaction outputs (UTXOs).
I am using BCOIN node.
Bcoin has given a API for /coin/address/:address but it is giving current balance as a result instead of history.

Looking at the docs, you're using the HTTP api incorrectly.
Try this in your terminal. Make sure to define or change the $url variable.
address0='RQKEexR9ZufYP6AKbwhzdv8iuiMFDh4sNZ';
address1='RHpAA3ZmmmWF6FW8qSfaEvh1jR1nUmVYnj';

curl $url/coin/address \
  -H 'Content-Type: application/json' \
  -X POST \
  --data '{ "addresses":[ "'$address0'", "'$address1'" ]}'

As per my understanding, it's the api to get UTXOs for multiple addresses. I want to get it for one address only.
Please check this :
address='R9M3aUWCcKoiqDPusJvqNkAbjffLgCqYip';
curl $url/coin/address/$address

What happens when you perform the req with only that address?

Also, I want to get the history of UTXOs of this address

It gives the current balance details of the address

I see the API you used now. What's your node's sync status?

Please mark this question solved then :D.
For transaction history submit another question as it's different from balance checking.


text:
What does the disabled field of the RoutingPolicy object mean in LND?
lnd v0.15.3-beta
The documentation for lnrpc.RoutingPolicy shows a boolean field called disabled, but it provides no definition of what that means. Each channel has 2 peers, and each peer in a channel has its own routing policy. Some of the channels have disabled set to true for one peer and false for the other.
Here is an example:
$ lncli getchaninfo 697113461880782849
{
    "channel_id": "697113461880782849",
    "chan_point": "094c1a9d6cd5294847f560758e8b8d8cdb4ef386ca746112536564742a92184b:1",
    "last_update": 1667018957,
    "node1_pub": "02572c2e1b43a78bb060e7d322b033443efc0d8d60fc2b111dd8bb999aa940d1f5",
    "node2_pub": "02a45def9ae014fdd2603dd7033d157faa3a55a72b06a63ae22ef46d9fafdc6e8d",
    "capacity": "5281151",
    "node1_policy": {
        "time_lock_delta": 40,
        "min_htlc": "1000",
        "fee_base_msat": "1000",
        "fee_rate_milli_msat": "10",
        "disabled": false,
        "max_htlc_msat": "5228340000",
        "last_update": 1665821197
    },
    "node2_policy": {
        "time_lock_delta": 24,
        "min_htlc": "1000",
        "fee_base_msat": "0",
        "fee_rate_milli_msat": "501",
        "disabled": true,
        "max_htlc_msat": "5228340000",
        "last_update": 1667018957
    }
}

Is it true that a channel is only active if the routing policy for both peers shows disabled = false?
Or is setting a routing policy to disabled the equivalent of setting it to null? Some channels have peers with null routing policies as in this example:
$ lncli getchaninfo 555817421567164416
{
    "channel_id": "555817421567164416",
    "chan_point": "43a329e374f19ac11cb8377d8d791505d27e60c221a3cfe99a2d758318803e0f:0",
    "last_update": 0,
    "node1_pub": "0207481a19a3f51a48f134e95afa67cfeffdb38a99b5ad3494a320c4918aaaf579",
    "node2_pub": "02ef61a252f9504a42fc264a28476f44cea0711a44b2da0bd729ad52aaee9d86b7",
    "capacity": "10000",
    "node1_policy": null,
    "node2_policy": null
}

Is the above channel active? If so, does it use default routing policy values?
Is disabled = true the same as a null routing policy? Or does it disable the whole channel if one node disables its routing policy?

The disabled field is a reference to an edge instead of the whole channel, but the api in lnd doesn't surface edges, so it must be inferred by the direction of fund movements.
Very quickly, what is an edge? In bidirected graphs (which the lightning network currently can be viewed as) what we consider a channel is actually comprised of two entities with direction, called edges.
For example:
┌────────┐               ┌────────┐
│        ├────edge 1────►│        │
│ alice  │               │  bob   │
│        │◄───edge 2─────┤        │
└────────┘               └────────┘

Okay, channels are really 2 edges. Why is that important? Well sometimes it's important to allow fund movement in a certain direction, without allowing movement in another. For example, a popular merchant node wants to allow people to send into their channel so they can collect money in a specific channel, without allowing people to forward through their node and move funds out of another channel. The merchant may want to do this if the specific outgoing channel is used for returns. People forward through that channel may up end the liquidity balance making it impossible to process returns to customers. But, crucially, they want to allow people to be able to send them funds in all directions (they are a merchant after all!)
Such precision is not given with our channels which are bidirectional, so we must look at tweaking the edges. Since we don't want to 'turn off' any channels completely, we cannot set any channel to inactive - this will not allow movement in any direction.
So to reiterate
All channels active and none disabled
┌────────┐               ┌──────────┐               ┌────────┐
│        ├────edge 1────►│          ├────edge 3────►│        │
│ alice  │               │ merchant │               │ carol  │
│        │◄───edge 2─────┤          │◄───edge 4─────┤        │
└────────┘               └──────────┘               └────────┘
            [active]                     [active]

All channels active and edge 4 disabled
┌────────┐               ┌──────────┐               ┌────────┐
│        ├────edge 1────►│          ├────edge 3────►│        │
│ alice  │               │ merchant │               │ carol  │
│        │◄───edge 2─────┤          │◄──X─edge 4──X─┤        │
└────────┘               └──────────┘               └────────┘
            [active]                     [active]

alice to merchant inactive and and edge 4 disabled
┌────────┐               ┌──────────┐               ┌────────┐
│        ├──X─edge 1─X──►│          ├────edge 3────►│        │
│ alice  │               │ merchant │               │ carol  │
│        │◄─X─edge 2─X───┤          │◄──X─edge 4──X─┤        │
└────────┘               └──────────┘               └────────┘
            [inactive]                   [active]


text:
multisig vs singlesig
Due to the Ledger debacle I have purchased a Coldcard hardware wallet. I made this decision partly based on watching the Antonopoulos live stream last week. Until now I have backed up my bitcoin on a single seed phrase stamped in metal. There are two copies which are securely stored at two different locations. I’m thinking of upping my security regarding the seed phrase.
My question is, does a 12 word ‘two of two’ multisig offer more protection than a singlesig 24 word? I would be storing the ‘two of two’ seed phrases together. Of course if the ‘two of two’ are found it’s game over. But, as talked about in Antonopoulos’ live stream I want to keep things relatively simple. What I am trying to achieve is a heightened level of security regarding vulnerabilities from a singlesig; whether that is in the form of a hack or some future unknown weakness in Coldcard’s TRNG.

The difference between 12 and 24 words seems to be a common misconception going around bitcoin.stackexchange.com/questions/118558/… it is completely irrelevant as to whether or not you are using multi-sig as well. Basically it is not useful to make comparisons across setups with different numbers of seed words because they will produce pubkeys that require the same number of rounds to crack in Pollards rho algorithm regardless of the input entropy. The seed words also don't restrict the usage of multi-sig in any way.