text:
Preventing theft of Bitcoin ATM
I am considering buying a Lamassu Bitcoin ATM machine.
The small machine is apparently "grab resistant". Does anyone know how the grab resistant mechanism works? Are there hooks on the back?

The page you linked to says "Internal steel vault is securely bolted to wall, stand, or countertop". Is that what you're looking for?

That's getting there, yes! A picture showing the bolting would be useful.

According to the website:

The machine will be smash and grab resistant. It is not meant for
  unattended or outdoor use, but it will have thick metal mounting
  plates, a dual locking system and an internal strong box for the cash.

According to this site:

The outer casing is a custom steel case made in Portugal. There’s a
  Protec cylinder lock holding it closed. Inside, there’s yet another
  steel case and another Protec lock. The tablet that runs the software
  has no open ports, and all outgoing connections are via https.

For either machine securely attach them to the surface they are sitting on. Bolt to the counter in a manner that can not be disassembled without opening the machine. For flow mounted machines secure to a concrete floor with large anchor bolts into the floor.


text:
My blockchain.info wallet was hacked. How can I create a double send to foil the attacker?
This is the transaction.
https://blockchain.info/address/1F8EP97jgQx8QD6XMRg2bCHHrJrZEMUTRt
Which is still unconfirmed.
I am trying to use https://coinb.in to create a double spend transaction with a higher fee but I am getting several errors such as:
18: txn-mempool-conflict OR
16: mandatory-script-verify-flag-failed (Script failed an OP_EQUALVERIFY operation)
How can I create a double spend transaction using https://coinb.in to block this attack?
In particular what goes in the transaction id field and the script field.

Looks like I managed to hack back my coins of the hacker by using electrum to do a double spend! :)))

Don't share your wallet seed with anyone, and beware of any website that asks for your seed.  That mybcdwallet website is a scam, see here:  https://bitcoin.stackexchange.com/questions/63688/is-the-bitcoin-diamond-wallet-website-bcdwallet-org-legit

Welcome to Bitcoin.SE! You can help the site by marking answers as accepted if they are correct and address the question so that the question does not remain as "unanswered".

So some background as to what happened here. I wanted to claim my bitcoin diamond air drop. I googled and this video came up first.
The video played this weird music which I think was hypnotic in some way. It instructed me to paste my blockchain.info restore phrase into this website: mybcdwallet.org.
I foolishly followed the instructions and did not realise at the time that I had handed over the restore phrase of my wallet to a hostile hacker. The next morning I woke up to find that a transaction had been initiated to transfer my bitcoins to another address (not owned by me!).
Fortunately the bitcoin mempool is clogged up with lots of transactions and the hacker used a small mining fee. Consequently the transaction had not been confirmed even though it had been initiated 10 hours before.
So what I did was installed Electrum wallet and restored my wallet into it. Electrum correctly assumed that I still had bitcoin in the wallet. I then basically did a "double-spend" i.e. I started another transaction of my own and sent the bitcoins to a paper wallet that I had created. I made sure that I used large mining fee to ensure that my transaction got processed before the fraudulent one.
The next morning I woke up to find that my transaction had been confirmed 13 times which means that I had taken back my bitcoin!
Lesson: Be very careful with your back up phrases. Don't type the phrase into a website you don't absolutely trust!
I'm not not sure if I can say the clogged mempool is a flaw of a design feature. But in this case it did save me a lot of money...

source: Stack Exchange

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

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

sort: votes


text:
Transactions that cannot be part of block
Is it possible to have a "unlucky" transaction that can never be part of block? Meaning grouping it with other transactions never results in a valid block?
[Edit]
By not being in valid block, I meant no valid nonce is found with given target difficulty. It seems mathematically, this is possible and what happens to transaction (if there is no expirey) in this case?

The number of possible blocks including that transaction is a number with tens of thousands of digits. You're imagining there would be no possible nonce for any of them?

No, if the transaction is valid then it can always be included in a block if a valid nonce/extra nonce is found.

No. By the definition, any valid transaction can be placed in block. If something in block invalidates it - this is only an array of random bytes, not a valid bitcoin transaction.

If you mean that the transaction may be pending for hours, or even days, yes: it can happen and it's part of Bitcoin Core protocol.
You may also want to have a look at this question

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


text:
Should USD savers be concerned about the rising popularity of cryptocurrencies?
I recently took an interest in cryptocurrencies.  Mostly, I'm interested Ethereum and Smart Contracts, but all the news about Bitcoin's rising price has prompted me to study currencies and economics in general.
The next generations are embracing this technology and it's only accelerating.
Should people that have spent a lifetime saving USD be concerned about the impact alternative currencies will have on the future value of their savings?

Let's compare the total size of circulating BTC to US dollars. According to coinmarketcap.com, the total value of all Bitcoin is 250 billion as measured in US dollars. Throw in Ethereum, Bitcoin Cash, IOTA, Ripple, Monero, Dash, Bitcoin Gold and Litecoin, and you're at 350 billion US dollars. (Bitcoin makes up the sizable majority of all cryptocurrency.)
Now compare to the total amount of US dollars. This one is a little harder to measure because what counts? When you keep a BTC in your wallet, that's just exactly one BTC. But if you keep $10,000 in a bank account, the bank usually loans some percentage of your money out to other people. Economists use varying "money supply" measures. In order of most to least conservative, there's M0 (just circulating paper money and coins), M1 (M0 plus demand deposits), M2 (M1 plus savings deposit and money market funds), M3 (M2 plus large corporate cash balances basically). Then you have near money-like instruments like foreign exchange reserves, treasury bills, short-term corporate paper, foreign currencies closely pegged to the dollar (like the Chinese Remnibi).
Let's just use M2 to get a reasonable lower bound. Currently that value is 13 trillion. So we can say that cryptocurrencies currently represent less than 3% of the total value of circulating US dollar and dollar like instruments.
To devalue the purchasing power of the dollar by 10%, at least 10% of the savings in M2 would have to shift to cryptocurrencies. (And most likely much more than just M2). That would represent an aggregate flow of 1.3 trillion. That would be a gain of 371% from current cryptocurrency capitalization. I.e. Bitcoin at $61,000.
And that's even assuming all the hypothetical new money flow comes from dollar savers only (and no European, Asian or Middle Eastern investors). Not to mention that not all Bitcoin investment is coming from money savers, a lot is coming from demand for speculative assets. In many ways the marginal Bitcoin investor is probably substituting for stocks and commodities. Not CDs and money market funds. More than anything, I'd say its gold and silver prices that probably are impacted the most by Bitcoin mania.
Another way of thinking about Bitcoin is figuring out which fiat currencies it actually sizes up to. Using the above methodologies, taking M2 money supply, all cryptocurrencies put together are still smaller than the Turkish Lira. (Which is about 400 billion USD).
TL;DR Cryptocurrencies at their current size are a pittance compared to major fiat currencies. To meaningfully affect the value of currencies like USD, EUR of JPY, Bitcoin will have to rise in value substantially compared to its current market capitalization. That doesn't mean it won't happen eventually, but current USD savers probably shouldn't be sweating unless the BTC bull market keeps running for a long time.

Well 371% gain could easily be seen in cryptos, Bitcoin alone made over 1000% this year...

So, you're saying that within a month or two we could see cryptocurrencies overtake the USD.  (Joking, a little, about the insane rise in valuations lately.)

@Kozuch - Possible, but remember every time Bitcoin gets larger it takes exponentially more money to keep moving the price up the same percentage. At the limit Bitcoin can't keep moving up 100% a year forever.

What exactly do you mean by "takes exp. more money"? Like exp. growths one after another?

Yeah. For Bitcoin to grow 1000% from $30 billion market cap to $300 billion market cap takes $270 billion influx of new investors. To grow another 1000% would take a $2.7 trillion influx. Since there's only a finite amount of money in the world, no asset can keep growing significantly faster than the general economy forever.

Considering that the US dollar has lost 90% of its purchasing power over the last 100 years you should be worried regardless of cryptocurrencies.

I'd be more worried, except that Bitcoin has shown it can gain or lose that much in a matter of days.  Given a choice between a predictable 3% annual inflation and a 10% day-to-day volatility, I know which I'd pick.

Move some of your savings into Bitcoin or etherium simply as insurance against hyperinflation.  BTC is not the threat to fiat currencies; Bitcoin is the lifeboat away from fiat currencies when they ultimately implode.
The more an imploding dollar worries you, the more to move into non-fiat assets like Bitcoin. The Fed has not stopped the printing presses. If that does not worry you, stay in USD, but keep a small amount of BTC or etherium just in case!

If you treat Bitcoin as a currency, it underwent a period of hyperinflation in early 2014 that would have ranked as one of the worst in history, and is currently undergoing a period of hyperdeflation that is unprecedented in economic history.

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


text:
Inserting *.dat file in new client
I'm running out of ideas and I'm hoping to get some help.
My computer crashed but I have the wallet.dat file on a thumb drive. I've downloaded and synced v0.18.1 on a new computer but don't see any way to add the .dat file using the GUI. Do I have to use the command line prompts? If so, the proper procedure would be very helpful.
I did see a similar situation on this forum but the advice given was over my head.
Thanks to anyone who can help.

You can just copy it to the bitcoin directory. What OS are you using?

Thank you so much JBaczuk for responding.
I finally figured out how to get to the directory; replaced the wallet.dat file with my saved file and it's now running and showing the proper balance.
It could be a bit easier process for us non-computer guys. :)
BTW, using Windows 10

great, agreed an entire wallet import feature would be nice.


text:
Fetch UTXO Bitcoin to address created by rpc importprivkey without rescan like other api
For few reasons, I must use rpc node to handle wallet at this time. In the near future, I will change the flow to use library to create addreses, store privatekey at database and create raw transaction. That means I will use rpc node for broadcasting only, not depend on it too much. But I need time to do, so I will divide this period to few parts, firstly, I will start at creating and store address:
I have both hex private key and wif key, then I use importprivkey to import wif key to rpc node without rescan because I have a large request contacting to rpc. If those addresses are fresh, it's very nice scenario, each new input to them will automatically fetch UTXO by using listunspent command to check.
In other case, the very worst scenario, for maintenance or backup, I import an address which contains old UTXO and wanna fetch these UTXOs to addresses without using rescan command (it takes a long time to complete), like other api just put address and get UTXOs in a blink.
https://testnet.blockexplorer.com/api/addr/myzhMVXT39L7nnco6TtJ2a7sYaEo8ixT4Q/utxo
Is there any ways to fetch old UTXO to address in rpc node without rescan? Because these api are very fast response, I think they're not using rescan. For long term, using other api is not good for my project, I'm using version 0.16 (I know it's very old but the project need time to change it slowly and carefully), thanks for help so much.

Because these api are very fast response, I think they're not using rescan.

No, they maintain massive databases that index every transaction and transaction output and their associated addresses. Bitcoin Core does not need this for normal function, and the vast majority of users do not need access to such information. Bitcoin Core does not and cannot build such databases.

I'm using version 0.16

Then there is nothing you can do.
If you were using 0.18, then you could use the scantxoutset command to just scan the UTXO set for UTXOs. This is very quick, and you can specify multiple addresses to do it as single batch scan. scantxoutset will give you all of the UTXOs for the specified addresses but will not add them to any wallets loaded in Bitcoin Core. However, it does not sound like you are using the wallet so that should be fine.

Thank you, I've understood. But I can not find more detail on this scantxoutset command. May you give me a simple format with a valid adress without publickey, example:
bitcoin-cli scantxoutset start '[{"desc":"MY_ADDRESS", "range":100}]'

bitcoin-cli scantxoutset start '["addr(<address>)", "addr(<address2>)"]' where <address> and  are the addresses you want to scan for. Since it is an array, you can just add more addr(<address>) style descriptors.


text:
Resolve BTC long mem pool (many unconfirmed tx)
I've started with Bitcoin exchange service, by creating rawtransaction and broadcast it. The problem which I must face to face is too long mempool chain (over 25 unconfirmed transaction).

Example:
64: too-long-mempool-chain

Using limitancestorcount and limitdescendantcount just resolve on local node, these late txs (transaction after first 25) must wait for a long period time to re-broadcast like this:
Transaction not found in Blockchain

Here is my testnet address has many unconfirmed txs and still pending hold, if I search on another explorer, I can't see 45 unconfirmed txs, same to getrawtransaction on node, response is No such mempool or blockchain transaction:

https://live.blockcypher.com/btc-testnet/address/mxHqrQBWuCndNaubTYUbcEVzeNPsT34TP6/

So, how can I avoid this issue, I just think few ways such as: Divide main address to few sub addresses which divides main UTXO to few UTXOs, create many-to-many transaction (currently is 1-2, 1 target and 1 changeAddress back), using high confirmation UTXO first,... Which options can bring better result and performance for a long time scaling up? Any advice is really appreciate. And last question, is there anyway to mark 1 UTXO that is used for 25 times (example I use UTXO X first, then it's returned Y, use Y is returned Z, total using X = 2, I don't have any related information to calculate it because node returns UTXO contains only txId).

Problem solved, make many sub UTXOs will resolve that well.


text:
reversing wallet to wallet transactions(both wallets mine)
I sent BTC from my coinb.in wallet to an electrum wallet on a tails drive, but I didn't realize it was the tails iso disk, and while waiting for confirmations, I noticed id' used the tails iso disk after the transfer but before I could get confirms and send BTC back to the coinb.in wallet, Tails froze.
So I had to reboot and that meant the tails iso disk went back to default, and the electrum wallet disappeared, so the BTC are stuck in blockchain because there weren't any confirms.
There's got to be a way to reverse so the coins go back to my coinb.in wallet. Both wallets are mine, so, it would seem like the transfer could be returned/reversed as there's no merchant and its not a refund. Thanks

bitcoin transactions can NOT be reversed.  If you have broadcast them and they have confirmations then you will need to get them out of the wallet you transferred them to.  If the transaction has 0 confirmations and is not being accepted on the network then you can do a -rescan of your wallet to get any old balances like this back.  Hope this helps.

If this question is still open, please add the relevant information from the comments to your question post. :)

The "owner" of a wallet is defined by whomever controls the private keys in that wallet.  If you have lost control of a wallet (the one on the ISO disk), then you are not the owner of that wallet anymore.  Nobody is.
If the transaction to the new wallet has not yet been confirmed and put into a block, you might have the option of replacing that transaction with one that goes back to your coinb.in wallet.  That depends on two things:

The transaction you want to replace has opted-in to Replace-by-fee
Your original wallet (coinb.in) allows you to use Replace-by-fee to broadcast a new transaction, replacing the original one

You can read more about it here:  https://en.bitcoin.it/wiki/Transaction_replacement

Thanks, yes I know the iso wallet is gone but I did make the key and have the 12 word seed, that's what I meant that it was mine, but now its gone.I'm learning the lingo.on blockchain.info, I saw the still unconfirmed transaction,a red box that said unconfirmed and a green one with the amount, is it still unconfirmed because I never clicked the broadcast button?I don't mind paying a fee(not too large).Should I open the top link first or read from the Wiki/transaction replacement link. Is there ifo I need to know in the bottom link?

If you still have the 12 word seed, then just restore the wallet somewhere else.  Don't worry about replacing the fee (if that's even possible in your scenario) unless you absolutely need the transaction to go through immediately.  If I were you, I'd simply restore the wallet and wait for the transaction to confirm.

I didn't click the broadcast box on coinb.in after sending. Does that mean it's possible to replace by fee?

I have absolutely no idea.  It is determined by how the site constructs transactions, and if they even have a ui for rbf.  You'd have to ask someone from the site.

to jestin. do you know that the same electrum wallet can be restored? I thought everything on tails iso gets erased. And both the tails iso and tails disks are now not working. No I don't absolutely need the transaction to go through. I just wanted the electrum wallet to be my main wallet because I wanted to use the Debian OS instead of Vista witch I'm on now beleive it or not.

@T.Mckenna'sghost, your 12-word seed can be used to recreate the wallet in its entirety...including transactions that haven't been confirmed yet.  This is the point of using an HD wallet with a 12-word seed.  So long as you have the seed, it doesn't matter what gets deleted.  You can always recreate it.  You can read the BIP for HD wallets here:  https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki

I read the links and I would need to find a step by step on how to replace by fee,unless it's simple enough for someone to explain it but I didn't get much from the links so I'm gonna google how to do that Rbf.Also When I download electrum wallet to windows,when I try to open the wallet it always says ,failed to open because side by side config.is incorrect see app. event log. Don't know what that means.

You are trying to troubleshoot too many issues at once.  First, forget rbf, since it sounds like you don't need it.  Just focus on restoring the wallet.  If electrum won't run, figure that out next.  If it tells you to check a log...then check the log.  Nobody can help you if you don't.  Once it's running, restore your wallet from seed.

Okay, I got an Electrum wallet to install (with errors). Could some body please help me out with what to do next,just send the funds back to my coinb.in wallet? Oh then click broadcast? any help is invaluable,and thanks to Jestin for help earlier.

To Jestin, I finally got an electrum wallet to install. And I followed your instruction to find my wallet,but it's got errors. It won't let me send the BTC to a wallet address I paste in the box, it has a different address when I preveiw it .

To Jestin, or anyone who read the whole question and thinks they can help. I finally got an electrum wallet to install. And I followed your instruction to find my wallet,but it's got errors. It won't let me send the BTC to a wallet address I paste in the box, it has a different address when I preview it . On blockchain and at first in the wallet, the amount was exact 0.09512741 (0.09512), then the amount in electrum  went up to 95+ BTC! Blockchain still has correct amount and address/other info.

I would move this to chat but I don't have reps.

At this point you should ask a new question, since you are troubleshooting something else.  It makes it easier for other people to find the answer.  Always remember that the point of this site is to create a knowledge base, not to troubleshoot individual issues.

Thank you for help, but should I stop adding comments here and just email

Any thoughts on how to force a wallet address of my choosing into the address bar in the send tab on these unstable electrum wallets I have to create . I don't know the address that's there, but it's not mine  and it doesn't erase and I can't paste over it, it's stuck. I need to buy some things with my BTC and can't from this/these wallets. Thanks.

I don't know about either Electrum nor coinb.in.  You would get more eyes on your follow up questions if you posted them as new questions.

LAST COMMENT FROM ME HERE  I would ask new questions, but people it seems who notice the new question asked , then start asking "why not just buy stuff from the wallet your BTC are in as they don't know the whole situation. Not saying I won't ask some new questions, They just won't know some details,and I'd feel like explaining everything. Thanks Jestin and all who've helped.

In the future please don't use comments for discussions but rather amend your respective posts to provide the additionally requested information. Also, I think that the required reputation is waved when a comment discussion gets moved to chat, otherwise please ping a moderator, so we can invite you to the chat manually.

It's a bit unclear which transaction confirmed happened, so I'll answer both possible scenarios:

If both transactions did not confirm, you should attempt to have your coinb.in wallet forget about the transactions, and send your coins from the coinb.in wallet to a new address on the coinb.in wallet, so that the old transactions become invalidated and don't confirm at a later time.
If the first transaction confirmed, but the second did not, you should either

restore your Electrum wallet somewhere else and create a new transaction to send the money where you want it.
create a child-pays-for-parent transaction, i.e. create a transaction in coinb.in that spends the unconfirmed transaction output you are trying to receive from the Electrum wallet. You'd need to add a larger fee as it needs to pay enough to make it worthwhile to include both transactions in a block.

Hopefully, this was resolved already, but perhaps someone else will be able to use the information. :)


text:
Java: bitcoinj; how to download a full block?
I would like to download a full block using Java and bitcoinj and then parse it to an array to be able to work with it. Here is some (very basic) pseudocode:
connect to network;
download latestBlock;
write/convert block to readable array;
read blockArray;
   sout: blockArray[23][55] // this should get me eg. a txid, address, ...
// or similar. I just want to be able to read values from the block

Is there a way to do this? I found the following solution here (Using bitcoinj to discover peers and download the block chain):
public class DumpLastBlock {
public static void main(String args[]) throws Exception {
    WalletAppKit kit = new WalletAppKit(MainNetParams.get(), new java.io.File("."), "test");
    kit.startAndWait();
    BlockChain chain = kit.chain();
    BlockStore bs = chain.getBlockStore();
    Peer peer = kit.peerGroup().getDownloadPeer();
    Block b = peer.getBlock(bs.getChainHead().getHeader().getHash()).get();
    System.out.println(b);
    }
}

Unfortunately, kit.startAndWait() isn't available anymore.
Can someone help me to get the latest block and be able to read its values?
Thank you very much :)

Example in bitcoinj source code is exactly what you are looking for:
BriefLogFormatter.init();
// Parse command line arguments
OptionParser parser = new OptionParser();
OptionSet opts = null;
List<String> nonOpts = null;
try {
    parser.accepts("localhost", "Connect to the localhost node");
    parser.accepts("help", "Displays program options");
    opts = parser.parse(args);
    if (opts.has("help")) {
        System.out.println("usage: org.bitcoinj.examples.FetchBlock [--localhost] <blockHash>");
        parser.printHelpOn(System.out);
        return;
    }
    nonOpts = opts.nonOptionArguments();
    if (nonOpts.size() != 1) {
        throw new IllegalArgumentException("Incorrect number of block hash, please provide only one block hash.");
    }
} catch (OptionException | IllegalArgumentException e) {
    System.err.println(e.getMessage());
    System.err.println("usage: org.bitcoinj.examples.FetchBlock [--localhost] <blockHash>");
    parser.printHelpOn(System.err);
    return;
}

// Connect to testnet and find a peer
System.out.println("Connecting to node");
final NetworkParameters params = TestNet3Params.get();
BlockStore blockStore = new MemoryBlockStore(params);
BlockChain chain = new BlockChain(params, blockStore);
PeerGroup peerGroup = new PeerGroup(params, chain);
if (!opts.has("localhost")) {
    peerGroup.addPeerDiscovery(new DnsDiscovery(params));
} else {
    PeerAddress addr = new PeerAddress(params, InetAddress.getLocalHost());
    peerGroup.addAddress(addr);
}
peerGroup.start();
peerGroup.waitForPeers(1).get();
Peer peer = peerGroup.getConnectedPeers().get(0);

// Retrieve a block through a peer
Sha256Hash blockHash = Sha256Hash.wrap(nonOpts.get(0));
Future<Block> future = peer.getBlock(blockHash);
System.out.println("Waiting for node to send us the requested block: " + blockHash);
Block block = future.get();
System.out.println(block);
peerGroup.stopAsync();

Please add the details of the link as it relates to the question in your answer. In the current answer, if the link ceases to work, future users will not be able to get any information from it.


text:
bitcoin-cli "getbalance" always returns 0
I have bitcoind running on windows and currently it's syncing the blockchain. Nevertheless, command getbalance always returns zero as value. Even if I seach for an address which has bitcoin.
E.g.
C:\Program Files\Bitcoin\daemon>bitcoin-cli.exe getbalance "[address...]"
0.00000000

Why does it always return 0? I would like to get the address balance of a specific address. I used an address from blockchain.info which had a balance before the current downloaded block.

getbalance only applies to addresses you own (and are in your wallet.dat).

Better: it only applies to the balance of your whole wallet. It doesn't take an address argument as input (only deprecated account names).

Can I search for addresses which are not in my wallet? Like check payment of address x?

No, Bitcoin Core doesn't maintain the expensive indexes for that.


text:
PHP: is there a way to convert a private ECDSA key to its corresponding public key?
As described here (https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses) I am trying to convert a private ECDSA key to its corresponding public key. (See step1 and step2).
I think I need some code which multiplies some coordinates on the elliptic curve. But I dont know how. Can someone help me, please?
// Unfortunately, this answer doesn't help me enough since I don't understand how to use the code. Can someone clearify that or give alternative solutions? Thanks

Yeah, you do "need some code which multiplies some coordinates on the elliptic curve" :). If you don't have extensive cryptography experience I would recommend you use library rather than trying to implement details yourself.
Googling I've found Bitcoin-lib-php. Looking at  the code it seems it seems this function does exactly what you are looking for.

Thanks! Unfortunately, I am not able to get this code running. I dont have classes in my php but the code you suggested does need classes and a lot of other stuff (composer ...). Is there a solution which is a bit easier? I am not able to implement this due to lack of programming skills .... :/

I created a small PHP library. You can do that using this class
You can use it like this:
require('secp256k1.php');
$Secp256k1 = new Secp256k1();

$public_key = $Secp256k1 -> private2public($private_key);


text:
Insight-api: Websocket "tx" event - which variables?
the Insight API has a websocket and publishes TX events as described here:
https://github.com/bitpay/insight-api (see bottom of this page)
The documentation says the names are:

tx: new transaction received from network. This event is published in
  the 'inv' room. Data will be a app/models/Transaction object. Sample
  output:

{
  "txid":"00c1b1acb310b87085c7deaaeba478cef5dc9519fab87a4d943ecbb39bd5b053",
  "processed":false
  ...                        <------------- ?????????
}

There is literally a "..." and I dont know the other names of the websocket!
How do I know the other names execpt txid and processed? There has to be some addresses, value and so on. Where can I find a list of these outputs?

What you are looking for is in the lib\transactions.js file. Line 210 to 215.

  var transformed = {
    txid: transaction.txid(),
    valueOut: valueOut / 1e8,
    vout: vout,
    isRBF: isRBF,
  };

I took a quick glimpse, vout is an array and isRBS is a boolean.
Honestly, I don't know why "processed" is in the documentation example. I might possibly have overlooked it, or maybe it could be a local produced string.

Thanks! I think there are more values in tx event. Value "processed" is a working value. I search for values like inputaddresses, outputaddresses, amout of btc and so on. Like every value which belongs to the transaction event.

I dug deeper now. You can take a look at https://github.com/bitpay/insight-api/blob/master/lib/index.js - line 283 to 289 . That's the transactionEventHandler . Look at the variables assigned to 'var result' , txid, valueOut, vout and isRBF are the only variables. So I can confirm nothing else. The "processed" is probably a dud.


text:
What is the fee policy suggested by the mainline bitcoin client?
The online wallet blockchain.info allows for the fee policy to be customised:

The "Normal" policy states
Follow the fee policy suggested by the mainline bitcoin client.

What is the fee policy suggested by the mainline bitcoin client explicitly?

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

Otherwise, the reference implementation will round up the transaction size to the next thousand bytes and add a fee of 0.1 mBTC (0.0001 BTC) per thousand bytes.

So the rate is 0.1 mBTC for each thousand bytes (rounded up) the transaction is.


text:
What is the queue position?
I have an unconfirmed transaction. (As an experiment, I didn't add a transaction fee, and the transaction is taking a lot of time to confirm.) This is some information from blockchain.info regarding the transaction:

The info "queue position 427" caught my eye. What exactly is the queue position?

It is most likely (blockchain may figure this out differently) the priority of the transaction compared to others. Nodes add highest priority transaction and repeat until they reach the block size limit.
https://en.bitcoin.it/wiki/Transaction_fees
priority = sum(input_value_in_base_units * input_age)/size_in_bytes


text:
How would a decentralised exchange work?
The idea of decentralised Bitcoin-fiat exchanges has been floating around. (For example Mastercoin, Ethereum and Bitshares claim to be able to do it.)
How would such a decentralised exchange work?

I think the idea is that certain Bitcoins can be representative of fiat. AKA smart property.

There is already a distributed exchange in production http://counterparty.co

I think this is a duplicate of http://bitcoin.stackexchange.com/questions/11116/what-is-the-definition-of-a-p2p-exchange/11303#11303 you can see my answer to that question.

https://www.cryptocompare.com/exchanges/guides/what-is-a-decentralized-exchange/

Apparently it's possible just with bitcoin. Here's a snippet from Vitalik Buterin's Ethereum white paper:

[Bitcoin] Scripts can also be used to pay bounties for solutions to computational problems, and one can even construct a script that says something like "this Bitcoin UTXO [unused transaction output] is yours if you can provide an SPV [simplified payment verification] proof that you sent a Dogecoin transaction of this denomination to me," essentially allowing decentralized cross-cryptocurrency exchange [emphasis added]. (Buterin, 2014)

So, it sounds like you could do decentralized exchange by basically bidding for other currency through your transaction outputs.
Buterin, Vitalik. "A Next Generation Smart Contract & Decentralized Application Platform" Ethereum White Paper. Updated August 2, 2014. Accessed August 13, 2014. https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-White-Paper

Concerning fiat, maybe you could build something like that on top of those services using escrow agents with user trust ratings?
I still haven't seen a good model. At some point you have to trust someone to hold the fiat. Who would you trust aside from a bank or similar institutions insured to protect your fiat?
This article on True peer-to-peer currency exchange explains how the people at Metalair envision one possibility.

Bob is looking to sell his bitcoins for Euros and enters a sell order
(ask) via the MetaLair network.
Alice is looking to buy bitcoins in
exchange for her Euros and enters a buy order (bid).
The MetaLair system connects Bob and Alice who both agree to use Ivan as the
escrow agent.
Ivan is a small time Europe based escrow agent who has a good trust rating via the MetaLair network.
Ivan acts as the escrow agent for the fiat funds and holds Alice’s Euros in his bank account! (Emphasis mine)
Ivan therefore also acts as the escrow agent for the Bitcoin transfer
which is done via the Bitcoin network using a 2 of 3 transaction. (or
this may be automated)
The Bitcoin transaction completes successfully.
Ivan transfers the Euros to Bob’s bank account. Ivan receives a fee for his services.

Would you trust Ivan, who is ultimately just some stranger, with a significant amount of your Euros?
In Ripple and Bitcoin – Foundations of a Decentralized Economy a similar model using Ripple is explained except that the trusted agents are really people you trust. But even in that case, how much fiat would you trust most of your friends with? More concerning, what happens when you have a $200 relationship with 20 friends and in one unlucky week you end up in debt for near the max to each one for a total approaching $4000, each of those friends having a real need for that money? These kinds of inevitable breakdowns lead to urban legends and an erosion of trust in the system.
Digging a bit deeper into Ripple, it has the concept of Gateways (very well illustrated at the link) which is defined as "any business that allows its customers to move money into or out of the Ripple network." Although it looks decentralized in theory, I don't see how it could be in practice. The future gateways will ultimately be today's exchanges: Mt. Gox et. al. The infrastructure doesn't do anything to change the nature of those companies.
Note that while at first glance Ripple looks decentralized, there is still at least one component (the UNL) which is maintained by a central authority. See this question for more details and the road map for making UNLs decentralized.
Although Ripple looks promising in terms of infrastructure all of these solutions fail to tackle the real challenge: how do you decentralize trust, accountability, and insurance against default?
For anything other than small amounts, history would tend to point to the average person only trusting large centralized institutions that are accountable to federal law and backed against risk by their government.

"Because Ripple is P2P software, no individual, corporation, or government controls it. The network operates via the combined effort of the Ripple software running all over the world." Care to debunk that claim?

https://ripple.com/wiki/FAQ#What_happens_to_Ripple_if_Ripple_Labs_goes_away.3F

Doesn't UNL = "Unique Node List"? If I understood right, the UNL is distributed already and each client has their own list? The issue at the moment seems to be with validators, all 5 of which are currently run by Ripple. Not exactly sure what validators are though...

Come on folks, at least leave a comment if you're going to downvote.

The Bitsquare project describes a system for the decentralized exchange of bitcoin for national (fiat) currencies.  The whitepaper goes into the details, but the gist is that the bitcoin being bought is first locked into a multi-signature (multsig) address and then the fiat payment is made directly from the buyer to the bitcoin seller using a traditional payment method (eg. bank transfer).
The three signatures on the multisig address are the buyer, seller and an independent arbitrator, pre-selected by both, which only becomes involved if there is a dispute about whether or not the non-bitcoin side has been settled as agreed.  Both buyer and seller also pay into the bitcoin multisig address a security deposit that is used to pay for active arbitration in case of a dispute.

I believe it could technically happen with Mastercoin/coloured coins linked to a Ripple account, and the coöperation of a Ripple gateway: he whom holds the coin can withdraw fiat whenever they wish, after the gateway verifies the ownership of the token.
Of course it'd add the question of trust in the gateway: that it will not fall for scams, will do an adequate validation of the coin's ownership, will be sufficiently solvent at any point in time, etc. As with anything involving fiat, this would be unavoidable.

Ripple includes a trading market, so what you are hinting at is essentially already available there.

Really? Wow, didn't know! Will have to explore Ripple much more...

Guide to Currency Trading on the Ripple Network


text:
Banking partners with UK Faster Payments
What is the easiest way to have access to UK Faster Payments facilities as a Bitcoin business? The UK banks have been quite hostile.
Can Bitcoin businesses have access to the Faster Payments network in the UK?


text:
MMCFE Not Reporting Stats from pushpool/wallet
I spent the last two days setting up a Litecoin Mining Pool and from what I can tell, absolutely everything is setup and working correctly. However, after creating a new worker and connecting to it, I have noticed that the stats on the website never update.
I have included my pushpool configuration below, but I am at a loss as to where the issue might be?
[root@test sbin]# vi server.json
{
        # network ports
        "listen" : [
                # binary protocol (default), port 8336
                { "port" : 8336 },

                # HTTP JSON-RPC protocol, port 8337
                { "port" : 8337, "protocol" : "http-json" },

                # HTTP JSON-RPC protocol, port 8339,
                # with trusted proxy appserver.example.com forwarding
                # requests to us
                #{ "port" : 8339, "protocol" : "http-json",
                #  "proxy" : "appserver.example.com" },

                # binary protocol, localhost-only port 8338
                { "host" : "127.0.0.1", "port" : 8338, "protocol" : "binary" }
        ],

        # database settings
        "database" : {
                "engine" : "mysql",

                # 'host' defaults to localhost, if not specified
                "host" : "localhost",

                # 'port' uses proper default port for the DB engine,
                # if not specified
                "port" : 3306,

                "name" : "mmcfe",
                "username" : "user",
                "password" : "pass",

                "stmt.pwdb" :
                  "SELECT password FROM pool_worker WHERE username = ?"
        },

        # cache settings
        #"memcached" : {
        #       "servers" : [
        #               { "host" : "127.0.0.1", "port" : 11211 }
        #       ]
        #},

        "pid" : "/tmp/pushpoold.pid",

        # overrides local hostname detection
        #"forcehost" : "localhost.localdomain",

        "log.requests" : "/tmp/request.log",
        "log.shares" : "/tmp/shares.log",

        # the server assumes longpolling (w/ SIGUSR1 called for each blk)
        "longpoll.disable" : false,

        # length of time to cache username/password credentials, in seconds
        "auth.cred_cache.expire" : 75,

        # RPC settings
        "rpc.url" : "http://127.0.0.1:9332/",
        "rpc.user" : "user",
        "rpc.pass" : "pass",

        # rewrite returned 'target' to difficulty-1?
        "rpc.target.rewrite" : true,

        # allow clients to update the ntime field of their work
        "roll.ntime.disable" : false
}

add after stmt.pwd this line
"stmt.sharelog" :"INSERT INTO shares (rem_host, username, our_result, upstream_result, reason, solution) VALUES (?, ?, ?, ?, ?, ?)"

and it should do the trick ;)
for litecoin you should remove the rewrite  into
"rpc.target.bits" : 18,


text:
Convert between String/Hex/Byte in Java for sha256 - wrong format?
I am trying to convert a bitcoin address and have the following code from here (Calculate Segwit address from public address, 2nd answer):
Step1: $ printf 1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9 > adr.txt
Step2: $ printf $( cat adr.txt | sed 's/[[:xdigit:]]\{2\}/\\x&/g' ) >adr.hex
Step3: $ openssl dgst -sha256 -binary <adr.hex >tmp_sha256.hex
Step4: $ openssl dgst -ripemd160  <tmp_sha256.hex
## result should be: 56379c7bcd6b41188854e74169f844e8676cf8b8

Now I want to do this in Java. I currently have the following code. No matter what I try, I dont get the correct result. :(
String address = "1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9"; // step 1
System.out.println("address: " + address);
String addressHex = toHex(address);
System.out.println("address hex: " + addressHex);
byte[] addressBytes = addressHex.getBytes(StandardCharsets.UTF_8); // step 2
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(addressBytes); // step 3
RIPEMD160Digest digest2 = new RIPEMD160Digest(); // steps 4
digest2.update(hash, 0, hash.length);
byte[] out = new byte[20];
digest2.doFinal(out, 0);
System.out.println("result: " + bytesToHex(out)); // = 62ab42cba5d2632d1350fafb2587f5d2ece445d3
                                                  // should be 56379c7bcd6b41188854e74169f844e8676cf8b8

Output:
address: 1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9
address hex: 314c383853323643356f796a4c31676b58734265597748486a764776436369647239
result: 62ab42cba5d2632d1350fafb2587f5d2ece445d3

Can someone help me? I think the problem is somewhere doing the conversion String/hex/byte ...? I tried really hard, but cannot find the correct way to do it.
I also tried to convert the address to hex and after that to bytes, but doesnt work neither. :/
// updated post
... still doesnt show the correct result :/
// update2:
byte[] address = ("1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9").getBytes();
System.out.println("address byte array: " + address);
String addressHex = bytesToHex(address);
System.out.println("address hex: " + addressHex);
byte[] addressBytes = addressHex.getBytes();
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(addressBytes);
RIPEMD160Digest digest2 = new RIPEMD160Digest();
digest2.update(hash, 0, hash.length);
byte[] out = new byte[20];
digest2.doFinal(out, 0);
System.out.println("result: " + bytesToHex(out));

Output
address byte array: [B@108c4c35
address hex: 314c383853323643356f796a4c31676b58734265597748486a764776436369647239
result: 62ab42cba5d2632d1350fafb2587f5d2ece445d3

Please read my answer in the original question you linked, the code you are trying to convert is wrong in the first place

Ok, here is the plain code for conversion from legacy to segwit:
    String addressToConvert = "1BGJEft81aaudqaCCcNnhsRQBA3Y96KYtx";
    byte[] decoded = org.bitcoinj.core.Utils.parseAsHexOrBase58(addressToConvert);
    // We should throw off header byte that is 0 for Bitcoin (Main)
    byte[] pureBytes = new byte[20];
    System.arraycopy(decoded, 1, pureBytes, 0, 20);
    // Than we should prepend the following bytes:
    byte[] scriptSig = new byte[pureBytes.length + 2];
    scriptSig[0] = 0x00;
    scriptSig[1] = 0x14;
    System.arraycopy(pureBytes, 0, scriptSig, 2, pureBytes.length);
    byte[] addressBytes = org.bitcoinj.core.Utils.sha256hash160(scriptSig);
    // Here are the address bytes
    byte[] readyForAddress = new byte[addressBytes.length + 1 + 4];
    // prepending p2sh header:
    readyForAddress[0] = (byte) 5;
    System.arraycopy(addressBytes, 0, readyForAddress, 1, addressBytes.length);
    // But we should also append check sum:
    byte[] checkSum = Sha256Hash.hashTwice(readyForAddress, 0, addressBytes.length + 1);
    System.arraycopy(checkSum, 0, readyForAddress, addressBytes.length + 1, 4);
    // To get the final address:
    String segwitAddress = Base58.encode(readyForAddress);

Functions (like org.bitcoinj.core.Utils.parseAsHexOrBase58) are taken from bitcoinJ library, as I mentioned earlier.
The resulting address is 3G7YPGDLLeaf1R36wrVxnSAhWMaA81oNhJ.
It can be checked here: Bip39 with mnemonic: "hood fatal cabbage proud lift amazing today mom disorder decorate eternal action punch finish drop thing chicken host erode bean rescue oblige mango double". To do that you should select "BIP49" and see the produced segwit address. Corresponding legacy address can be found at BIP32 tab, but you should manually insert derivation path m/49'/0'/0'/0. Note that private keys for them are equal: L38zkVFvLmVmHTpFdqfSP2WrQ1qcZnB829rthRS1rRexcc7RKuHr
Your address 1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9 is converted to 39gGJc9HiemSJwpa2smXgCXMW8y9FNzFDe.

How can I give you 10M upvotes? Thanks! Works perfectly! TY TY TY!

I have not the Java solution, but I can indicate the error. The conversion to hex is apparently missing.  When I do the hash on the text file itself, I also get the wrong result:
$ printf 1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9 > adr.txt
$ openssl dgst -sha256 -binary <adr.txt >tmp_sha256.hex
$ openssl dgst -ripemd160  <tmp_sha256.hex
(stdin)= db151e871af66b1323893e3f527e22f7684718af

so the transformation into a hex byte array "addressHex" is for sure missing something.
Update:
I can see the "bytesToHex()" function, was this the code from the link I provided in the other thread? If so, try to dump the output of your java into a file, and use hexdump to verify. So you can concentrate on these two lines (I made the sed command shorter, without "cat"):
$ printf 1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9 > adr.txt
$ printf $( sed 's/[[:xdigit:]]\{2\}/\\x&/g' adr.txt ) >adr.hex
$ hexdump -C adr.hex
00000000  31 4c 88 53 26 c5 6f 79  6a 4c 31 67 6b 58 73 be  |1L.S&.oyjL1gkXs.|
00000010  59 77 48 48 6a 76 47 76  cc 69 64 72 39           |YwHHjvGv.idr9|
0000001d

Here you should receive the same result by your java code, then you'd be good to go :-)

Thanks, I edited my code but it still doesnt work. I have also edited my post to now show the new code.

see my update, that's so far all I can do ...

Please listen to my answer in the other thread, the approach is completely wrong from the start and you may end up losing funds if you use it. You should not be hashing the address at all

Address is in Base58 format. So, if you want to fet hex representation, you should firstly convert base58-address string to byte array and then convert it to hex string. bitcoinJ library has utilities for that, you can find all of the conversions there.

Thanks! I tried to implement your suggestion but I am still not able to get the correct result. I updated my post ("update2"). ty!


text:
Is there a minimum size of network for a cryptocurrency to be viable?
I am not a technical person, so easy answers will be greatly appreciated.

What is the relevant unit for size of the network for this question? Nodes? Miners? Wallets? Users?
If a cryptocurrency has a very small network, e.g. 10 users, will it have 'technical' (not marketing) problems to function as a currency? (Like protection against hacking, efficiency of transaction speed and cost, etc.)
If yes in #2, what size of network would be required? 1000? 10,000? 100,000?

This question is too broad. It depends on the currency's system. And the figures are rather arbitrary.
Let's focus on bitcoin's proof of work system. Processing power (of miners) is required here to confirm transactions. Protocol adjusts processing power needed to confirm transactions depending on the current processing power.
If total processing power is low it is easy for attacker to enter the network with large processing power (comparable to total current processing power) and execute attack.
So it is important to have huge processing power in the network and that it is as much as possible distributed among the miners.
What is considered huge is arbitrary. What is considered sufficiently distributed is also arbitrary. Currently in bitcoin you have large mining pools that you can considered each a single miner. Don't know how many of these together at the moment have processing power comparable to all other miners.
If 10 mining pools have over 50% of network processing power they can (in some scenarios) collaborate and execute attacks.

Thank you very much for the answer. So you think a matrix of scale and difficulty rather than just scale is a right measure.


text:
What makes bitcoin decentralized?
I want to understand the defense mechanism of the Bitcoin price control.
A rich company can buy a large portion of Bitcoins from different people in different exchanges. Then they can hold on to those Bitcoins, essentially becoming a controller of the Bitcoin economy. A large number of companies can start doing that.
If that becomes the case, then will Bitcoin still be decentralized? Those companies with their fare share of the Bitcoins, can control the price or any other aspect of the economy.

Say they do.
First, in the process, they'd push the price of bitcoins way up. And this is while they're buying. So they'd be buying high -- not a very good strategy. Every bitcoin holder would be quite grateful to them.
Now, they start taking over control of bitcoin. Let's just assume somehow they could do this. Well, if they make bitcoin more valuable, good on them. If that makes it less useful for some things that are important to people, that's no problem, they can just create another system or use some other existing system like bitcoin cash or litecoin.
If they crash the value of bitcoin because people don't want a centralized system, well then they just bankrupted themselves. They bought all these bitcoins high and now they're worth much less. And everyone else can still move to another system.
So it just seems like a way to waste a lot of money, unless they can make bitcoin better and more useful. In that case, awesome. Either way, all the people who sold bitcoins to them as they bid the price way up will have plenty of money to build a new system that they have no influence over.

It seems that you are suggesting that holding a large amount of Bitcoins does not matter much for a company. The reason is: they would either have to sell those Bitcoins, essentially demoting Bitcoin's value or just to hold on to those Bitcoins, which would result into non-transactions and hence of no use.
I can buy your argument. Still, a lot of people could face risk. Also, if Bitcoin becomes a significant part of mainstream economy, risk of some company affecting the economy has some high probability. Is it Bitcoin's strength that it's outside the mainstream economy?

@soham.m17 Someone can create disruption, but only at their own expense. That's already the case today. Jeff Bezos could, if he wanted to, divert much of America's productivity to moving dirt with teaspoons for quite some time. People who invested in other businesses might even lose lots of money. But for very sensible reasons, people don't worry too much about this.

Yeah. I understand it now. Your explanation makes things more clear. Thank you.

I think you're not understanding what decentralized exactly means.
Sure, a company with a large stake can control the price ( up to a certain degree), but this does not mean that they control (the protocol) Bitcoin itself.
There's no central power which decides what transaction is good, or which one is bad, or who controls what.
which would still be the case even if company X had 90% of the bitcoin supply.

Okay. That's a different definition of decentralization. Still, there could be a situation where a company with large stake of bitcoins would be able to influence the policies of Bitcoins, and hence the transactions.

Policies are usually only changed by consensus, which is determined by the signaling of full nodes, i don't think this necessarily has that much to do with how much bitcoin you own.

Isn't it contradictory what you are saying? Because if a company can start controlling large share of mining nodes and also hold large share of Bitcoins, they can become the controlling authority. I'm not arguing against Bitcoin's potential. I want to understand what restricts the companies controlling this currency.

Miners, even a majority of them, don't control Bitcoin. Their authority is restricted to determining the order of otherwise valid transactions, and deciding which of conflicting transactions get accepted. This power includes the ability to indefinitely reject some transaction, but under no circumstances can miners make an invalid transaction acceptable - network nodes would simply ignore their blocks if they did.


text:
Is proof-of-work required in Bitcoin?
It seems that the rationale behind the proof-of-work requirement in Bitcoin is that it creates trust in a decentralized trustless network by:

helping to reach consensus on which version of the blockchain is the correct one in case that there are multiple temporary competing forks.
making the accepted blockchain computationally immutable (irreversible).

Question: Why is proof-of-work required for creating trust?
If most users are honest, then they would voluntarily enforce the prohibition to rewrite the blockchain.
If most users are dishonest, they can still rewrite the blockchain, even with the proof-of-work requirement, not just by outperforming the honest miners, but even simply by creating a consensus to accept a new fork of the main blockchain as the correct version of the blockchain.
UPDATE: Here is the article I linked to in my question:
http://hackingdistributed.com/2014/06/19/bitcoin-and-voting-power/

Bitcoin and Voting Power
Emin Gün Sirer
June 19, 2014 at 05:56 PM
I see a common mistake in many discussions centered around Bitcoin
  involving voting power. Specifically, many people think that Bitcoin
  works kind of like a majority voting system, which it kind of does.
  They then go on to conflate mining power with voting power, and
  believe that someone with 51% mining power has ultimate say over the
  contents of the blockchain. In this blogpost, I want to clear up this
  misconception. The truth is that it is the Bitcoin users who wield
  ultimate power, and the miners' hashing power has absolutely no say in
  determining how the protocol evolves.
There are two kinds of "voting power" in Bitcoin: mining power and
  chain power, and the latter is what really matters because it, solely,
  on its own, determines how the Bitcoin protocol evolves. The best
  analogy I can come up with is from soccer: the owner of a soccer team
  seems all powerful and may appear to have total control over
  administrative decisions, but it's ultimately the fans who are fully
  in charge. Fans routinely kick out bad management, drive away players
  and override bad decisions by the seemingly powerful administration,
  for it is the fans' attention that the administration seeks.
In any case, let's not let too much anthropomorphizing get in the way;
  that's why most people get trapped into conflating these two concepts
  in the first place. Technically, there are two kinds of consensus
  decisions taking place in Bitcoin:
Mining Power
Miners engage in a process by which they append transactions to the
  end of an append-only log known as the blockchain. For this, they are
  amply rewarded with 25 BTC per block, plus all the transaction fees in
  this block. The process is carefully constructed to enable the
  majority to form behind a single, unforgeable blockchain. Any given
  miner can refuse to honor a block discovered by another miner, but if
  he's in the minority (<=49%) position, he will ultimately find himself
  being overtaken by the majority.
Among miners, an entity with 51% or more of the hashing power is in a
  privileged spot. He can engage in behaviors that are not available to
  minority miners.
But a >=51% miner does not get to rewrite the rules of Bitcoin. That's
  because mining power is different from, and is not at all correlated
  with, chain power.
Chain Power
The Bitcoin ecosystem consists of many people other than the miners
  who operate on the blockchain. In particular, every single Bitcoin
  user, every single person with a wallet, and every single merchant
  operates on the blockchain. They store their balances on the
  blockchain (or have an exchange store their balances somewhere on the
  blockchain). They use the blockchain to check the balances of people
  who are sending Bitcoins to them. They validate Bitcoins all the way
  back to their creation using the blockchain. Miners are part of this
  group, but they are just like every other user. Collectively, we'll
  call this group the Bitcoin community.
Everyone in the Bitcoin community gets a single vote, no more, no
  less, on what kind of a blockchain they will accept. Miners are
  subservient entities who must follow the decision of the Bitcoin
  community. They get one vote, along with everyone else. In fact, it is
  entirely possible for the Bitcoin community to completely change the
  rules that govern the maintenance of the blockchain, and do so without
  having any of the miners agree (this would be a mistake for political
  reasons, but the statement holds technically). The rules are
  determined entirely by what the buyers and sellers accept as the
  legitimate blockchain. Miners are subservient followers.
To illustrate, suppose that I, for whatever reason, decided to change
  the blockchain rules so that every new block generated after January
  1st, 2016 shall have the number 42 at the top of every block. If I see
  a block after that date that does not have 42 on top, I discard it.
  Suppose that I could get merchants and wallet holders to agree to this
  pointless, but illustrative, change -- perhaps they also agree that
  6*7 is a magical number and they want every block blessed by this
  magic. Then we'd just collectively refuse the blocks miners create
  without the magic number in them. The work that the miners would put
  into creating non-42-bearing blocks would be wasted, and their
  compensation, in Bitcoins, on a blockchain that none of us accept,
  would be worthless. New miners would emerge who place the magic number
  on every block, have their blocks recognized, and be able to redeem
  their block rewards at merchants who recognize the new blocks with 42
  on top.
The basic way in which people exercise this power is by respecting, or
  ignoring, the blockchain. And the vote carries as much weight as what
  that user has to offer to the rest of the community. If the user is
  offering to buy a lot of other Bitcoins, or if he's a merchant like
  Overstock.com selling stuff that people want, then people will want
  their blockchain to be compatible with him, and he will have greater
  sway. The core devs working on the reference implementation play a
  critical role here, because they get to decide the de facto set of
  rules that everyone abides by.
Implications
This is a tremendously empowering situation. A 51% miner does not have
  51% of the vote; in fact, GHash has just as much say over the contents
  of the blockchain as do I, or you, or anyone else. Miners derive their
  income from the buyers and sellers who recognize the blocks they
  create. This is why the behavior of a misbehaving miner is proscribed
  -- they could not, for instance, create 10 million Bitcoins out of the thin air, because no one would recognize those new rules. The
  blockchain is what we all say it is.
This is why regular users wield ultimate power in Bitcoin. It is the
  chain power that determines the shape of the blockchain, not mining
  power. Miners are followers, not leaders, in this game.
It is critical to keep these distinctions in mind as we think about
  the true source and distribution of power in the Bitcoin system. There
  are lots of fuzzy analogies for Bitcoin (and I'm guilty of using
  analogies wherever possible myself, because they do make the discourse
  more accessible, but they also lead some people astray), and if one's
  not careful, it's easy to end up conflating mining power, which
  corresponds to miner speed, with real power, which corresponds to
  having something people want, like cash to buy Bitcoins with or goods
  to sell for Bitcoin. It's the latter that counts and dictates all
  else.

Possible duplicate of Why do we need Proof of Work in bitcoin?

Proof of work does not create trust. It creates incentive.
Miners are paid if their block is eventually part of the main version of history ("blockchain") that the network accepts. They must irrecoverably burn electricity in order to create blocks, which costs them money; money they only get paid for if their block "wins".
These factors together mean that miners have a strong incentive to cooperate with other miners, instead of having each try to construct their own version of history, because ultimately only one version will be accepted (ignoring things like intentional forks in the network).
Proof of work is also used for a much more logistical, but equally important purpose: denial of service protection. Because the minimum difficulty for a block scales with the network's hashrate, it is enormously expensive for someone to produce more blocks than (on average) 1 per 10 minutes. Without an objective measure of work like PoW (or central trusted set of parties) anyone could spam the network with an unboundedly large amount of blocks to validate.

Comments are not for extended discussion; this conversation has been moved to chat.

If most users are honest, then they would voluntarily enforce the prohibition to rewrite the blockchain.

Without proof of work, this is just not possible. There would be no limit to the number of blocks that could be created at about the same time, there could be thousands of them created every minute. Different servers might receive them in different orders. And a server that was down for a day would have no way to know what to accept.
You need some way to agree on which of two or more equally good ways the system can make forward progress will be agreed upon. Proof of work is not the only way to do this, but you need some way.
In addition, there would be no way to do the initial distribution of the bitcoins as they're created.

Comments are not for extended discussion; this conversation has been moved to chat.

Question: Why is proof-of-work required for creating trust?
If most users are honest, then they would voluntarily enforce the prohibition to rewrite the blockchain.

If everyone was honest, then we wouldn't need a blockchain system at all. We could all just trust one another to remember our account balances, and update them appropriately as we transact with one another throughout the day.
Unfortunately, not everyone is honest, and so we need a system that allows everyone to remain in consensus about the current state of the network (ie the allocation of coins). Creating a system that can do this without trusting some central authority is very difficult, as exemplified by the Byzantine generals problem.
Bitcoin's PoW system provides the incentives for miners to work on extending a single chain (rather than proposing alternate histories), and as others have written here, it crucially provides a mechanism of selecting which miner will add the next block to the network.

If most users are dishonest, they can still rewrite the blockchain, even with the proof-of-work requirement, not just by outperforming the honest miners, but even simply by creating a consensus to accept a new fork of the main blockchain as the correct version of the blockchain.

Based on the comments you have made, I think you have misinterpreted the article you linked to. That article uses very non-rigorous language to explain how the network reaches consensus at a high level, but upon more rigorous inspection it fails to provide a blueprint for an alternative system. '1 user = 1 vote' is a very simplified explanation of how the networks consensus rules are chosen, but it is the miners that must extend the chain according to these rules. A network of regular users (nodes) can all agree to follow some certain set of rules, but they cannot come to consensus on which chain to follow without PoW mining. I believe this is the source of your misunderstanding: the article is not suggesting that the network's nodes can continue to remain in consensus without the miners, it just provides a simplified explanation of how users define the rules which miners must adhere to.
Even if users collectively decide to enforce a new set of consensus rules, they will still require the PoW miners to create a blockchain for them. Without the PoW mining, users will be unable to reach consensus, because there will be no mechanism for agreeing upon which block will be the next block, or for mitigating against DoS attacks.

Let us continue this discussion in chat.

Suppose there's a zero proof-of-work cost. i.e., creating a block is free, computationally. (In practice, this is impossible, but please bear with me). If creating a valid block is free, then here's a way to "buy" something without actually spending any Bitcoin:

You buy something using bitcoin. The block recording the transaction is added to the blockchain.
You receive the item.
You mine a lot of blocks on before your transaction. Because this is much longer than the branch containing your transaction, this means that the branch that doesn't contain your transaction becomes the valid branch.

Thus, the transaction log blockchain won't actually contain the transaction where you sent the Bitcoin to buy something.
There are two ways to prevent this sort of attack:

You have an authoritative source that stores the transaction log, thus the new branch won't have been made valid. This method implies centralisation, which is contrary to the goal of a decentralised currency.
You make it infeasible for a single user to generate more blocks than the other users combined, and thus make the transaction log without the attacker losing money the valid log.

Enter proof-of-work. This is an attempt to use method 2 to prevent this attack. The system of users will be generating blocks. This takes a huge amount of processing power. In order to make more blocks than the system of users, the proof-of-work forces you to use more computational power than the rest of the system of users combined.
How about a timestamp?
A timestamp is easily forged. With the above attack, you could create a block with a timestamp before the "lose money" transaction. Then, the attacker could send the Bitcoin elsewhere (another one of his/her wallets), and the next block (the "lose money" transaction) would be invalid because it's saying "Take 0.1 bitcoin from X's empty wallet to give to Y."
Two methods of preventing this from happening:

The timestamp is verified by an authoritative source (which implies centralisation)
The timestamp is only valid if received a fixed (short) time after the timestamp (then the vendor only needs to wait for the required time to elapse, then the block is set in stone and is not in risk of invalidation).

There's a few problems with method 2. First, a blockchain requires all the blocks to be present in memory in order to figure out how much a given wallet contains. When you're reading the block from a log, how would you know if the block was received less that fixed time after the timestamp? The log could be falsified, unless there's an authoritative source or the log takes too much computational power to create by a single malicious user. The latter is guaranteed for any long blockchain with a strong proof-of-work.

The article linked argues that the end user controls the rules of BitCoin, much as the fans of a Soccer/Football team controls how the management of the team behaves.
The question argues that, because the majority of end users can change the rules, if a majority of end users are dishonest, the proof-of-work system becomes useless because the group of end users can rewrite the BitCoin system for their benefit. Furthermore, the question argues that if the majority of users are honest, they can maintain a consensus whether or not the proof-of-work system is present. Therefore, the question argues, since proof-of-work is useless if the majority of end users are honest, and it is useless if the majority of end users are dishonest, proof-of-work is in itself useless.
The question is a three part argument:
If:

A majority of end users being dishonest leads to them rewriting BitCoin to their benefit, and
A majority of end users being honest allows them to maintain consensus with or without proof-of-work,

Then:

Proof-of-work is useless

Though I disagree with the second point, the asker believes it true, and there has been a debate on this point ongoing since September 18, 2019 to at least October 7, 2019 in the linked chat room. Upon conclusion of this debate, this answer shall be edited to elucidate the reasoning behind why point 2 is or is not correct.
I also disagree with the first point. Here's why:
Let's assume that the dishonest majority came together and somehow came to an agreement on what the new rules of BitCoin would be. These new rules would be advantageous to all of them, of course. We'll liken these new rules to "drawing an evil moustache on the BitCoin", and we'll call the new system, with the new rules, MoustacheCoin.
If MoustacheCoin is beneficial to the dishonest majority at the expense of the recipient, then no one would want to sell anything for MoustacheCoin. MoustacheCoin would therefore have reduced purchasing power in comparison to BitCoin. If MoustacheCoin is beneficial to the dishonest majority at the expense of the sender, then no one would want to use MoustacheCoin to buy anything, and thus it would be useless. If MoustacheCoin were only beneficial to those in the founding dishonest majority, then no one new would join. Furthermore, it is axiomatic that MoustacheCoin would be not detrimental to the founding dishonest majority, because then that person would not be in the founding dishonest majority.
Therefore, MoustacheCoin would not be useful, due to either 1: having a reduced purchasing power in comparison to BitCoin, 2: no one being willing to buy anything with it, or 3: giving no competitive advantage against insiders, but outsiders don't want to join.
MoustacheCoin wouldn't even kill BitCoin, even if it remained nine times as popular as BitCoin. After all, even if nine of ten people prefer apples to oranges, there's still money to be made selling oranges.
And, as described above, there's no way MoustacheCoin would be as useful as BitCoin.
Therefore, point 1 in the argument is defeated; a majority of end users being dishonest would not lead to them rewriting BitCoin to their benefit.
If most users are honest, then as the system currently stands, proof-of-work is required to maintain consensus in the face of a dishonest minority. The asker disagrees (as of October 7), and a debate is ongoing.
The argument (as of October 7) appears to be currently deadlocked, with the state of the argument from this answerer's perspective being this:
BitCoin uses proof-of-work to prevent a double-spending attack, which can theoretically be overcome if an attacker controls more than half of the mining power in the network. The asker proposes an alternative system not including proof-of-work, instead relying on a voting scheme as detailed below:

Each user maintains a list of other known users and what it believes is the most updated chain.
If the user sees a new longer chain that is compatible with its "most updated chain", then the user's "most updated chain" becomes this new longer chain.
If the majority of the user's known users agree on a chain that is incompatible with the user's current chain, then the the user's "most updated chain" becomes this new chain.

Where compatible is defined as the shorter chain being a subset of the longer chain.
The objection that a human user can potentially forge a large number of false virtual users and thus "win the vote" to cause a double-spending attack has been raised.
The asker has responded that it is equivalently possible in BitCoin, an assertion that I strongly doubt.
It seems from the current state of the debate that this question is raised due to a misunderstanding of the article.
My interpretation of the article is this: BitCoin users have soft influence over the rules of the blockchain, because if they collectively decide to not recognise the rules and instead recognise a new set of rules, there is no value in for miners to follow the old set of rules. In this manner, it is entirely possible for the users of BitCoin to change the rules of BitCoin.
The interpretation of the asker seems to be more along these lines: BitCoin has a technical mechanism that allows a majority of users to change the rules. The asker seems to believe that this can lead to a potential attack where a majority of users (many of which can be controlled by a single natural person) can potentially compromise the network.
This debate is ongoing, and this answer will update at its conclusion.

Proof of work is not required, there are other algorithms such as proof of stake that are still decentralized (though I don't know how it works even though Ethereum wants to use proof of stake mining). The proof of work gives a block a difficulty, saying "there must be at least X zeroes in a block." (X does not have to be an integer, if it did, difficulty could only be adjusted on orders of two, four, or sixteen; right now it is a little above 16.8) This adding zeroes controls the number of problems that can be solved, and is usually on the order of hundreds or (lower) tens of hundreds per day. When there are more miners, the network responds relatively soon by raising difficulty (in less than 2 weeks), and when there are less, it also responds by doing the opposite (in possibly more than 2 weeks). The proof of work is like a lottery, and who solves the problem is randomly selected and is then awarded the prize through the coinbase. Proof of work is basically a verification mechanism that looks at the zeroes in a hash (work) and forces a certain number (minimum) to be zero.


text:
How would a bitcoin transaction fits into a double entry accounting
A bitcoin transaction may have multiple input and multiple output. When we have a multiple input and multiple output scenario. Also, we might not be able to identify from which address the transaction fees original from.
SO how is that possible that we take bitcoin transaction from blockchain directly and fit into a traditional double entry accounting bookkeeping, taking transaction as below.

As a third party with only the public blockchain data, there is likely no way to accurately fit a random Bitcoin transaction into the double-entry accounting method. This is because a single Bitcoin transaction could represent the economic activity and payments of many different people, or of many different transactions. To say this differently: transaction inputs/outputs do not necessarily map 1:1 onto users/transactions. There are ways to create Bitcoin transactions such that any one transaction can represent a larger amount of economic activity (more people and/or payments involved), especially in consideration of higher level protocols such as the Lightning Network, federated sidechains, etc.
As an example, a coinjoin transaction is intentionally designed to make it nearly impossible to determine who the owner of the newly created UTXOs is. Even those that are party to the transaction itself would only have knowledge of their own involvement, the nature of the other inputs/outputs would be unknown to them. Here is an example of a coinjoin transaction.
Another example is a lightning network channel: in this case a couple of on-chain Bitcoin transactions could represent a potentially unlimited set of payments, but all of those payments will be happening off-chain, and so they cannot possibly be known just by looking at the Bitcoin blockchain. Here is an example of a lightning network transaction, there is no knowing how many payments were sent over this payment channel (unless you were party to the channel, of course). Here is a look at that channel, but from a lightning network explorer.

SO how is that possible that we take bitcoin transaction from blockchain directly

You cannot, unless you have additional information about the transactions you are attempting to catalogue. Generally, this sort of info is only known to those that are party to the transaction, so you should be able to accurately account for your portion of involvement in any transactions you are involved in, but to do so for every transaction in the blockchain is ultimately impossible. Too much potential nuance and detail is not explicitly stored in the blockchain record (and for good reason, privacy and fungibility is important).

Also, we might not be able to identify from which address the transaction fees original from.

There is no concept of 'which address fees originate from' inherent to the blockchain record, for more info see my answer here.


text:
In Python RPC Calls, How is vout Address Derived for P2PK transaction?
How is the vout address derived for a P2PK transaction?  I am using the Python API that ships with the bitcoin source code, in directory bitcoin/test/functional. I'm using regtest.
I have written a unit test.  It creates a transaction, writes the CTransaction object to the log file, then appends a CTxOut object to the vout array, and writes the CTransaction object to the log again.  The second log entry shows that the item in the vout array includes an array of addresses containing a single value, 'muXtVbAXxTdAdaS9HQLnexRvsfgVteZcv8'.  How was that value derived?
Here is the relevant code fragment:
    addr1 = w0_rpc.getnewaddress()
    self.log.info(f"\n    DEBUG addr1={addr1}")
    a1 = w0_rpc.getaddressinfo(addr1)
    pubkey1 = hex_str_to_bytes(a1['pubkey'])
    self.log.info(f"\n    DEBUG pubkey1={pubkey1}")
    p2pk1 = CScript([pubkey1, OP_CHECKSIG])
    self.log.info(f"\n    DEBUG bytes_to_hex_str(p2pk1)={bytes_to_hex_str(p2pk1)}")
    tx1 = CTransaction()
    tx1.vin.append(CTxIn(COutPoint(int(txid0, 16), v), b""))
    s = pprint.pformat(w0_rpc.decoderawtransaction(ToHex(tx1)))
    self.log.info(f"\n    DEBUG tx={s}")
    tx1.vout.append(CTxOut(int(9 * COIN), p2pk1))
    s = pprint.pformat(w0_rpc.decoderawtransaction(ToHex(tx1)))
    self.log.info(f"\n    DEBUG tx={s}")

Below is the log output from that code.  You can see at the end that the vout array contains an item which includes an array of addresses containing a single value, 'muXtVbAXxTdAdaS9HQLnexRvsfgVteZcv8'.  I did not explicitly provide that value, at least not knowingly.  It seems to me that the value was derived somewhere, under the hood.  Where did this happen?  How was the value calculated?
    DEBUG addr1=2NGYQt1CxwSCdGbj8mpxMtLaTZtxHsmbqWM
2019-10-10T12:13:06.176000Z TestFramework (INFO):
    DEBUG pubkey1=b'\x02#\x9c\xabCVRL\xc1\xd1o8}\x0e\x85Z myQ-&\x06\xb2\xc2\xea \xfa\xf0(\xd3e\x98'
2019-10-10T12:13:06.176000Z TestFramework (INFO):
    DEBUG bytes_to_hex_str(p2pk1)=2102239cab4356524cc1d16f387d0e855a206d79512d2606b2c2ea20faf028d36598ac
2019-10-10T12:13:06.177000Z TestFramework (INFO):
    DEBUG tx={'hash': '0abb1fa572d89323429fc231fcede74af58f77469a3b383ee856db60ecee41a4',
 'locktime': 0,
 'size': 51,
 'txid': '0abb1fa572d89323429fc231fcede74af58f77469a3b383ee856db60ecee41a4',
 'version': 1,
 'vin': [{'scriptSig': {'asm': '', 'hex': ''},
          'sequence': 0,
          'txid': '9d177bb43b76dcbbf52fad079c4fd98986b32034d91ea12bcb4e67d32dc20f9b',
          'vout': 0}],
 'vout': [],
 'vsize': 51,
 'weight': 204}
2019-10-10T12:13:06.179000Z TestFramework (INFO):
    DEBUG tx={'hash': 'd86153fc539e699289dc8f7f4e20d10f6378fa4f10dad131f5c8b2d4bc7e5c76',
 'locktime': 0,
 'size': 95,
 'txid': 'd86153fc539e699289dc8f7f4e20d10f6378fa4f10dad131f5c8b2d4bc7e5c76',
 'version': 1,
 'vin': [{'scriptSig': {'asm': '', 'hex': ''},
          'sequence': 0,
          'txid': '9d177bb43b76dcbbf52fad079c4fd98986b32034d91ea12bcb4e67d32dc20f9b',
          'vout': 0}],
 'vout': [{'n': 0,
           'scriptPubKey': {'addresses': ['muXtVbAXxTdAdaS9HQLnexRvsfgVteZcv8'],
                            'asm': '02239cab4356524cc1d16f387d0e855a206d79512d2606b2c2ea20faf028d36598 '
                                   'OP_CHECKSIG',
                            'hex': '2102239cab4356524cc1d16f387d0e855a206d79512d2606b2c2ea20faf028d36598ac',
                            'reqSigs': 1,
                            'type': 'pubkey'},
           'value': Decimal('9.00000000')}],
 'vsize': 95,
 'weight': 380}

Edit: Thanks to the response below, I was able to work out how the value of the address is derived.  This code does the trick:
    from test_framework.script import hash160
    from test_framework.address import byte_to_base58
    addr1_hash160 = hash160(pubkey1)
    self.log.info(f"\n    DEBUG addr1_hash160={addr1_hash160}")
    addr1_base58 = byte_to_base58(addr1_hash160, 111)
    self.log.info(f"\n    DEBUG addr1_base58={addr1_base58}")

So for the given example, this code prints out 'muXtVbAXxTdAdaS9HQLnexRvsfgVteZcv8', the value of the address that appears in the output from decoderawtransaction().  As mentioned below, this value is not actually relevant for a P2PK transaction.

The script inside the transaction output contains the address because this is a unique method for check the owner of the transaction. ps: not only the script P2PKH contains the address but also P2SH, P2WPKH, P2WSH.  Only the script P2PK does not contain the address but the real public key.

How was the value derived?

The address derived to the parsing and apply the correct codify to the hex propriety inside the ScriptPubKey. so if you parsering this 2102239cab4356524cc1d16f387d0e855a206d79512d2606b2c2ea20faf028d36598ac it contains the address

P2PK scripts don't actually have addresses, it is really a bug that an address is shown for P2PK outputs that has been fixed for Bitcoin Core 0.19 (to be released soon) and later.

Given a public key, you can derive an address from it by hashing the public key first with SHA256, then that hash with RIPEMD160. This result is known as the hash160. The hash160 is then encoded with Base58Check Encoding with a version number of 0 for mainnet, and 111 (hex 0x6f) for testnet.
You can also derive other address types from a public key, i.e. bech32 addresses for a P2WPKH script. However, either way, it is incorrect to say that a P2PK output has an address.

I got it, many thanks.  Based on the info that you provided, I was able to work out the code to derive, from the public key, the address that appears in the output of decoderawtransaction().  I edited my question to include the code.  I understand that the address value is not relevant for a P2PK transaction.  I take it that the address is derived in bitcoin core - in the call to decoderawtransaction(), I suppose - and not in the Python layer.


text:
How do I sign a transaction in Python?
How do I sign a P2SH transaction in Python?  I am using the Python API that ships with the bitcoin source code, in directory bitcoin/test/functional.  I'm using regtest.
Here is a fragment of my unit test, it works as I expect.  It creates a transaction, signs it, and broadcasts it:
    tx2 = CTransaction()
    # txid0 is the ID of a previous TX, v is the index of the relevant output:
    tx2.vin.append(CTxIn(COutPoint(int(txid0, 16), v), b""))
    # For now, send to a dummy address:
    tx2.vout.append(CTxOut(int(9 * COIN), CScript([OP_TRUE])))
    tx2 = w0_rpc.signrawtransactionwithwallet(ToHex(tx2))["hex"]
    #tx2.vin[0].scriptSig = CScript(signature, public_key)
    txid = n1.sendrawtransaction(tx2, True)

Instead of making the call to signrawtransactionwithwallet(), I would like to explicity assign a value to tx2.vin[0].scriptSig.  I gather that this value should look something like (signature, public_key), but I can't figure out how to do it.
How do I go about this?  Is there any documentation of this Python library?  So far I am looking at the existing Python test cases, and following the docs for the Bitcoin RPC interface.
Edit.  I managed to accomplish this by reverse engineering the existing unit tests.  I was able to use CScript objects and did not need to go as low level as the approach in the accepted answer, although it's good to know that that option exists if I need it.  Here is the code for a unit test which 1) pays to a P2SH that is locked with two signatures and 2) spends from that address without calling signrawtransactionwithwallet(), instead manually assigning a signature to tx.vin[0].scriptSig.
#!/usr/bin/env python3

import pprint

from test_framework.test_framework import BitcoinTestFramework
from test_framework.messages import CTransaction, CTxIn, CTxOut, COutPoint, ToHex, COIN, sha256
from test_framework.script import CScript, CScriptOp, OP_1, OP_DROP, OP_2, OP_3, OP_HASH160, OP_EQUAL, hash160, OP_TRUE, OP_DUP, OP_EQUALVERIFY, OP_CHECKSIG, OP_CHECKMULTISIG, OP_CHECKSIGVERIFY, SignatureHash, SIGHASH_ALL
from test_framework.util import hex_str_to_bytes, bytes_to_hex_str
from test_framework.address import byte_to_base58
from test_framework.key import ECKey

class RawTxTest(BitcoinTestFramework):

    def set_test_params(self):
        self.num_nodes = 2
        self.extra_args = [[],["-txindex"]]

    def run_test(self):
        """Implement a P2SH transaction with OP_CHECKSIG without using signrawtransactionwithkey()"""

        self.log.info(f"\n    DEBUG START")

        # initialize node variables
        n0 = self.nodes[0] # This node used for initial balance
        n1 = self.nodes[1] # All test wallets created on this node

        # TRANSACTION #0 - pay from node 0 to addr0
        w0 = n1.createwallet(wallet_name="wallet0")
        w0_rpc = n1.get_wallet_rpc('wallet0')
        addr0 = w0_rpc.getnewaddress()
        self.log.info(f"\n    DEBUG addr0={addr0}")

        txid0 = n0.sendtoaddress(addr0, 10.0)
        n0.generate(6)
        self.sync_all()

        # dump the tx to the log
        raw_tx0 = w0_rpc.getrawtransaction(txid0, True)
        s = pprint.pformat(raw_tx0)
        self.log.info(f"\n    DEBUG tx0={s}")

        # write the balance to the log
        bal0 = w0_rpc.getbalance()
        self.log.info(f"\n    DEBUG bal0={bal0:f}")

        # TRANSACTION #1 - Pay from addr0 to P2SH
        coinbase_key0 = ECKey()
        coinbase_key0.generate()
        coinbase_pubkey0 = coinbase_key0.get_pubkey().get_bytes()
        coinbase_key1 = ECKey()
        coinbase_key1.generate()
        coinbase_pubkey1 = coinbase_key1.get_pubkey().get_bytes()
        #redeemScript = CScript([coinbase_pubkey0, OP_CHECKSIG])
        redeemScript = CScript([coinbase_pubkey0, OP_CHECKSIGVERIFY, coinbase_pubkey1, OP_CHECKSIG])
        redeemScriptHex = redeemScript.hex()
        self.log.info(f"\n    DEBUG redeemScriptHex={redeemScriptHex}")
        redeemScript160 = hash160(redeemScript)
        madd1 = byte_to_base58(redeemScript160, 196)
        self.log.info(f"\n    DEBUG madd1={madd1}")
        p2sh_script = CScript([OP_HASH160, redeemScript160, OP_EQUAL])

        tx1 = CTransaction()
        vout = [v["n"] for v in raw_tx0["vout"] if addr0 in v["scriptPubKey"].get("addresses", [])]
        assert len(vout) == 1
        v = vout[0]
        tx1.vin.append(CTxIn(COutPoint(int(txid0, 16), v)))
        a1 = w0_rpc.getaddressinfo(madd1)
        self.log.info(f"\n    DEBUG a1={a1}")
        scriptPubKey = a1["scriptPubKey"]
        pubkey1 = hex_str_to_bytes(scriptPubKey)
        tx1.vout.append(CTxOut(int(8 * COIN), p2sh_script))

        priv0 = w0_rpc.dumpprivkey(addr0)
        tx1 = w0_rpc.signrawtransactionwithkey(ToHex(tx1), [priv0])["hex"]
        txid1 = n0.sendrawtransaction(tx1, True)
        n0.generate(6)
        self.sync_all()

        # dump the tx to the log
        raw_tx1 = w0_rpc.getrawtransaction(txid1, True)
        s = pprint.pformat(raw_tx1)
        self.log.info(f"\n    DEBUG tx1={s}")

        # write the unspent tx to the log
        w0_rpc.importaddress(madd1)
        us1 = w0_rpc.listunspent()
        self.log.info(f"\n    DEBUG us1={us1}")

        # TRANSACTION #2 - Pay from P2SH to addr2
        addr2 = w0_rpc.getnewaddress()
        self.log.info(f"\n    DEBUG addr2={addr2}")
        a2 = w0_rpc.getaddressinfo(addr2)
        pubkey2 = hex_str_to_bytes(a2['pubkey'])
        p2pkh2 = CScript([OP_DUP, OP_HASH160, hash160(pubkey2), OP_EQUALVERIFY, OP_CHECKSIG])
        tx2 = CTransaction()
        tx2.vin.append(CTxIn(COutPoint(int(txid1, 16), 0)))
        tx2.vout.append(CTxOut(int(7 * COIN), p2pkh2))

        (sighash, err) = SignatureHash(redeemScript, tx2, 0, SIGHASH_ALL)
        sig0 = coinbase_key0.sign_ecdsa(sighash) + bytes(bytearray([SIGHASH_ALL]))
        sig1 = coinbase_key1.sign_ecdsa(sighash) + bytes(bytearray([SIGHASH_ALL]))
        #tx2.vin[0].scriptSig = CScript([sig0, redeemScript])
        tx2.vin[0].scriptSig = CScript([sig1, sig0, redeemScript])
        #tx2.rehash()
        txid2 = n0.sendrawtransaction(ToHex(tx2), True)
        n0.generate(6)
        self.sync_all()

        # dump the tx to the log
        raw_tx2 = w0_rpc.getrawtransaction(txid2, True)
        s = pprint.pformat(raw_tx2)
        self.log.info(f"\n    DEBUG tx2={s}")

        # write the balance to the log
        bal2 = w0_rpc.getbalance()
        self.log.info(f"\n    DEBUG bal2={bal2:f}")

        self.log.info(f"\n    DEBUG END")

if __name__ == '__main__':
    RawTxTest().main()

To manually build scriptSig you need to concatenate the length of the signature, the signature, the length of the pubkey and then the pubkey in binary form.
For example, let's take a look at a random TX I happen to have open on my console:
./bitcoin-cli getrawtransaction 055f9c6dc094cf21fa224e1eb4a54ee3cc44ae9daa8aa47f98df5c73c48997f9 1

We want the vin:
    {
      "txid": "b187426f2fdd5a7ac2f49d822f68e07f48486ee53a8a45de2494f12acb37a0d8",
      "vout": 3,
      "scriptSig": {
        "asm": "3046022100d78c31a20fa11533475be893b229eb4d252e600dcc2a0735d360c541b6aec813022100e3eaa72c915ef47d94ccbd18c2ba6d9ae5b98be6e9fbf968d4bbbb003e06d687[ALL] 030e001332b43924be343986cca3df669f57b0dedd120990e727787f8dea50fdbc",
        "hex": "493046022100d78c31a20fa11533475be893b229eb4d252e600dcc2a0735d360c541b6aec813022100e3eaa72c915ef47d94ccbd18c2ba6d9ae5b98be6e9fbf968d4bbbb003e06d6870121030e001332b43924be343986cca3df669f57b0dedd120990e727787f8dea50fdbc"
      },
      "sequence": 4294967295
    }

As you can see there are two formats for scriptSig: hex and assembly language. The assembly language is simply the hex with interpreted opcodes. Notice how hex has a leading "49" before the assembly format? 0x49 is 73 in decimal, which tells it to push 73 bytes onto the stack. After the 49 and 73 bytes (146 characters), we see 0x21 which is 33 in decimal. So we push 33 bytes onto the stack (the remaining 66 characters). This completes the scriptSig part of the unlocking script: pushing the sig and the pubkey onto the stack.
(Note that in hex encoding each character encodes 4 bits, so a byte takes 2 chars. That's why when pushing 33 bytes you see 66 characters on the hex encoding, for example.)
To build your own scriptSig from the above data, you need to decode the hex into binary byte array:
myscript = bytearray.fromhex(script_hex)
tx2.vin[0].scriptSig = myscript

In your case you don't have the hex yet because you're building the TX yourself, so what you need to do is build a byte array yourself and attribute it to tx2.vin[0].scriptSig
In Python pseudo-code:
# assuming signature,pubkey are byte arrays
# otherwise you need to encode them first
mybytes = [len(signature)] # initial byte = signature length
mybytes.append(signature)
mybytes.append(len(pubkey))
mybytes.append(pubkey)
tx2.vin[0].scriptSig = mybytes

On the Python API source code you can see that the definition of scriptSig is binary so if you get the above steps right your TX should work.

I can't thank you enough for that thorough response.  I managed to accomplish what I needed with a slightly higher level approach.  I just updated my OP to include the code.  I'm glad to know about the lower level approach in case I ever need it.