Connect with us

# How Bitcoin Addresses are generated? Understand the Math behind Bitcoin

To use Bitcoin, user generally needs two things: Private Key and Bitcoin Address.

Published

on

The following content was written by webtricks on February 04, 2020, 05:05:40 PM in the thread How Bitcoin Addresses are generated? Understand the Math behind Bitcoin. All content is owned by the author of the bitcointalk.org post. (original)

Ok! So let’s start with the topic. To use Bitcoin, user generally needs two things: Private Key and Bitcoin Address. Bitcoin Address is an identifier which looks like this: 18J6ai34uzGofUuzbiwhXJzKzdx1efDBqA. User have to share it with sender to receive payment. Whereas private key is a key which user have to input in wallet to access the funds received.

You may be already knowing what I have just said above. But did you ever wonder how these pair of keys are generated? Let’s dive deep into topic and create our own code for generating key pair. The main and the most important component of Bitcoin Address is Private Key. Let’s discuss it first:

Private Key

In simple words, anything can be private key if it fulfills two conditions. Condition one, it must not be 0. Second, it must be lower than the value of N defined by SECG for secp256k1 curve. However, the value of N is very, very large so practically every 256-bits number is valid private key.

Now the question arises how to generate private key. As I said in the starting that anything can be private key. For example, this string: “I am a string to generate private key” can be converted into private key. All you have to do is, to convert this string into 256-bits value and check if it is lower than the N.

But is it suggested to generate private key this way? Actually no! It is popular saying that human is the worst random generator. If we use custom strings or numbers like this, it may be possible that someone else uses the exact same string which may result into compromise of private key. So better be safe than sorry and only rely on random generators to generate private key.

But again another problem arises. Most of the generators such as Math library of Javascript (Math.random() function) use fixed patterns to generate random number. So using such generators will generate more miseries than keys.

So what is the ultimate solution? The best way is to use the keys generated by wallets but if you want to independently dive into the quest, use secure generators like this one:  strong pseudorandom generator.

Enough said on private keys, let’s go to bitaddress.org and generate an address. First we will create address on bitaddress.org and then try to create the same through our own code to learn the mathematics behind key generation.

Here is the key pair I generated. You may find that there are more than one format for both public key and private key. Let’s discuss about them in brief before jumping to the coding part:

This is the P2PKH format of bitcoin address. It is widely used for sending/receiving bitcoins. Public Key once generated through Elliptic Curve cryptography is then hashed using sha-256 and ripemd-160 algorithm and later checksum is attached in the end of hash which forms public address. We will try to achieve that later in this thread with real code.

2. WIF Private Key

WIF or Wallet Import Format is the format of private key in which wallets such as Electrum import private key. If you paste the bare hex of private key then Electrum won’t open the wallet. You have to convert private key into WIF format to use it in wallets. We will write code to convert private key into WIF too.

3. Uncompressed Public Key

Ok! So I haven’t discussed so far how public key is generated. The process is actually complex. We take a special generator point defined as G by SECG which is located on secp256k1 curve i.e. one of the elliptic curve. Then we multiply this generator point with private key. The resulting multiplication will give us two coordinates, one is X and the other is Y. Uncompressed Public Key is nothing but : 04 + X + Y. So first two numbers of public key are 04 which signifies that key is uncompressed. Next 64 characters (32 bytes since every 2 characters of hex make 1 byte) are X coordinate and last 64 characters (32 bytes) are Y coordinate. Total length of uncompressed public key is 130 or 65 bytes.

4. Compressed Public Key

Since, it is possible to find Y coordinate if X coordinate is given. So we generally drop the Y coordinate from our public key. Hence, last 64 characters are removed. As a result, compressed public key is made up of 66 characters (32 bytes). First two characters can be either 02 or 03 (instead of 04) and the next 64 characters (32 bytes) will be X coordinate. If the value of Y coordinate is even then 02 is put. If the value of Y coordinate is odd then 03 is put. In the above photo, the value of Y-coordinate was odd so we have 03 in our key.

As we discussed earlier the private key must be 256-bits or 32 bytes (8 bits = 1 byte) which is when converted into hexadecimal form is of 64 characters. So you can convert any value into hex and it will be of 64 characters. This is very handy for our bitcoin code because we will use hex form of private key to start generating key pair. So as I was saying earlier that we can even use strings like “I am a string to generate private key” to generate private key, so here is the secret. We will first convert such strings into hex and then use 64 characters of hex to generate key pair.

6. Private Key Base64 Form

Not very popular format of private key. But we can even encode/decode our private key into Base64 using native conversion.

Enough for the head start. Now let’s dive straight into code and generate the above key.

As I am fan of Javascript (because I think it is the easiest programming language and can be used in full-stack development), I will be using JS in Node.JS environment for this guide. But if you are comfortable with other language then you can easily interpret my JS code into your code. At last, if you aren’t comfortable with coding at all then leave that, just read the text and pictures below and I promise you will have the best idea on how keys are generated.

Before starting let’s prepare the setup. First step is to create a folder. Inside folder create a file with .js extension. File name can be anything like index.js or app.js.

Once the above steps are done, open the folder in Visual Studio Code and head to your terminal. There is inbuilt terminal in Visual Studio Code, you can use that too. If not, you can use native terminal of Mac or Windows but make sure you have opened the folder in terminal. Once folder is opened in both Visual Studio Code and terminal, run the following commands in terminal to install 2 dependencies for the project:

Code:
npm init -y
npm i ripemd160 –save
npm i bs58 –save

We need two hashing and one encoding functions in our code namely sha256, ripemd160 and base58 apart from elliptic curve cryptography. sha256 is already present in native crypto library of nodejs. We can either code other two on our own or just import them. For the simplicity of this guide, we installed ripemd160 and bs58 npm packages above and will use these in our code. I have verified the source code of both packages and it’s completely safe to use these in code.

Now let’s start the real fun. Open your file and start with the code. The code is in chronological order. The Step 1 code will go at the top of file and step 2 code will start where step one code ends and so on:

Step 1. Creating hashing functions

Code:
const crypto = require(‘crypto’);
const RIPEMD160 = require(‘ripemd160’);
const BS58 = require(‘bs58’);

const sha256 = input => crypto.createHash(‘sha256’).update(input).digest();

const ripemd160 = input => new RIPEMD160().update(input).digest();

const bs58 = input => BS58.encode(input);

Ok! So in first three lines of code, we have imported the code of all three hashing and encoding functions in our file. Next, we created functions for these. It is not mandatory to create functions but in that case we have to write whole code again and again whenever we need to hash something. For example, if we don’t write these three functions then every time we have to create sha256 hash of something we have to write crypto.createHash(‘sha256’).update(something).digest() but with above code, we just have to write sha256(something) from next time. Cool? Let’s move forward.

Step 2. Creating Elliptic Curve Function

Code:
const generateECPoints = privateKey => {

const Pcurve = BigInt(‘0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F’);

const Gx = BigInt(‘55066263022277343669578718895168534326250603453777594175500187360389116729240’);
const Gy = BigInt(‘32670510020758816978083085130507043184471273380659243275938904335757337482424’);

const G = [Gx, Gy];

const modInverse = (a, n) => {

a = (a % n + n) % n

const dArray = [];
let b = n;

while(b) {
[a, b] = [b, a % b];
dArray.push({a, b});
}

if (a !== BigInt(1)) {
return null;
}

let x = BigInt(1);
let y = BigInt(0);

for(let i = dArray.length – 2; i >= 0; –i) {
[x, y] = [y,  x – y * BigInt(dArray[i].a / dArray[i].b)];
}

return (y % n + n) % n;
}

const modOf = (a,b) => {
const r = ((a % b) + b)% b;
return r;
}

const ECAdd = (a,b) => {
const lamAdd = modOf((b[1] – a[1]) * BigInt(modInverse(b[0] – a[0], Pcurve)), Pcurve);
const y = modOf((lamAdd*(a[0] – x) – a[1]), Pcurve);
return [x, y];
}

const ECDouble = a => {
const lamda = modOf(((BigInt(3)*a[0]*a[0])*(modInverse(BigInt(2)*a[1], Pcurve))), Pcurve);
const x = modOf((lamda*lamda – BigInt(2)*a[0]), Pcurve);
const y = modOf((lamda*(a[0] – x) – a[1]), Pcurve);
return [x, y];
};

const ECMultiply = (genPoint, pvtKey) => {
const scalarBinary = BigInt(‘0x’+pvtKey).toString(2);
let GP = genPoint;

for (let i=1; i < scalarBinary.length; i++) {
GP = ECDouble(GP)
if (scalarBinary[i] === ‘1’) {
}
}
return GP;
}

return ECMultiply(G, privateKey);
}

The above code is my version of Elliptic Curve Multiplication. This maybe only pure Javascript coding of elliptic curve you will find on the entire internet. I think it would be inappropriate to explain the whole above code in this thread as the main motive of this thread is to generate key pair. So for now use the above code as it is. I will create separate thread for Elliptic Curve Cryptography after 3-4 days and explain the same above code in that thread.

Step 3. Generating X and Y coordinates of Public Key from above function and Private Key

Code:
const privateKey = “6EBD5FAB742ED0734B37C63BD2A3CE8797FE4AC63C9A99781F8BEDDF6307094E”;
const publicKey = generateECPoints(privateKey);

In this step we have taken the hex value of private key (5th item from the image) and put it in generateECPoints function as created in Step 2. This will give us X and Y coordinates of Public Key which will look like this:
[26552980488606060638326679080566574626825610331305555186819497546906082384636n, 106820354128014061768597493909158935631153585355120117243602895828064095418195n]

You may notice n at the last of each coordinate. This n means we are dealing with extra large numbers here, known as Big Integers in Javascript. Also you may notice that these coordinates are not matching the X and Y in the image above. Well, we have generated numbers for now. We have to convert these into hexadecimals to get uncompressed key and compressed key. Let’s do that in next step.

The following content was written by webtricks on February 04, 2020, 05:06:05 PM in the thread How Bitcoin Addresses are generated? Understand the Math behind Bitcoin. All content is owned by the author of the bitcointalk.org post. (original)

Step 4. Creating Compressed and Uncompressed Public Key

Code:
const checkKey = key => key.length < 64 ? ‘0’.repeat(64 – key.length) : key;

const publicKeyX = checkKey(publicKey[0].toString(16));
const publicKeyY = checkKey(publicKey[1].toString(16));

const uncompressedKey = ’04’+publicKeyX+publicKeyY;

let compressedKey;
if (publicKey[1]%BigInt(2)===BigInt(1)) {
compressedKey = ’03’+publicKeyX;
} else {
compressedKey = ’02’+publicKeyX;
}

Bingo! We have achieved the first target. We have created uncompressed and compressed public key. In the code above, we have first of all created checkKey function. This function is doing an interesting thing. It may be possible that while converting X and Y coordinates from number to hexadecimal that the resultant length of X and Y is not 64. But as we discussed previously that the length of uncompressed key is 130 where first two characters are 04 then 64 characters of X and then 64 of Y. So it fill the void, we are adding zeros if length is lower than 64. For example, if the length of X is 63 characters, we will add one 0 to make it 64.

Then we defined hexadecimal value of X coordinate as publicKeyX and Y as publicKeyY. You may see we using toString(16) in second and third line. This code is converting number to hex and then overall wrapper of checkkey is checking if the length is lower than 64 then add 0, if not then return same key.

Then we defined uncompressed key as uncompressedKey and then compressed key as 03+X if Y is odd and 02+X if Y is even.

Step 5. Generating P2PKH Key

Before starting with code let’s discuss the process of generating P2PKH key. It is to notice that uncompressed and compressed key we generated in step 4 was not Bitcoin specific. There are several other services like Gmail or Facebook using Elliptic Curve cryptography to create public/private keys. However, this very step is where we will convert our public key into Bitcoin-specific format i.e. P2PKH. Following is the pictorial representation of the process, yes the artist is back

So we start with uncompressed key as generated in step 4 (we can also start with compressed key which will generate different P2PKH address but can be used interchangeably and belongs to same private key). Next we perform sha256 on the uncompressed key. Then ripemd160 hashing on the previous. Then we add 00 in front of previous hash. This is our 21-bytes of binary address. To generate next 4-bytes of binary address. We have to perform double sha256 hashing on first 21 bytes. Take the first 4 bytes of resulting hash i.e. first eight characters of the resulting hash and add it in the end of 21 bytes. Finally we get 25-bytes Binary address and we have to convert this into Base58 code. Now let’s see the final code.

Code:
const keyHex = Buffer.from(uncompressedKey, ‘hex’);
const ripedHashedKey = ripemd160(sha256(keyHex));
const mainRipeKeyString = ’00’+ripedHashedKey.toString(‘hex’);
const mainRipeKey = Buffer.from(mainRipeKeyString, ‘hex’);
const doubleHashedKey = sha256(sha256(mainRipeKey)).toString(‘hex’);
const checkSum = doubleHashedKey.substr(0, 8);

The above code is nothing but the same 8 steps I detailed in picture above. Bingo! We have successfully generated our Bitcoin Address. Now let’s move to final step and generate our WIF private key from hexadecimal of private key.

Step 6. Generating WIF from Private Key

Similar to the previous approach, let’s discuss the process before actually moving to the code. Generating WIF from private key is actually simpler than previous step. Converting raw hex of private key into WIF actually has many benefit. First it is smaller and simpler than raw hex. Second it has inbuilt-checksum to verify that private key is valid. Let’s see the pictorial representation from artist first:

First step is simple, we are taking hexadecimal form of private key and adding 80 in front of it. Note that all these addition we are making throughout code isn’t actually numbers. They are hex codes, for example, 80 here when converted to decimal form is 128. Ok next, we are performing double rounds of sha256 hashing. Then we take first 4 bytes of the resultant hex and add them at the end of extended hex of private key. Finally we perform Base58 encoding on the result and we get our WIF key. Code time:

Code:
const pvtKeyExtended = “80”+privateKey;
const extended = Buffer.from(pvtKeyExtended, ‘hex’);
const hashedExtended = sha256(sha256(extended)).toString(‘hex’);
const checksum = hashedExtended.substr(0, 8);
const finalHex = pvtKeyExtended+checksum;
const WIF = bs58(Buffer.from(finalHex, ‘hex’));

Nothing special in code this time too. We are simply performing all six steps as mentioned in picture above. If you have any doubt regarding any code, you can ask in thread or PM me.

Good work! We have finally completed the process and generated our Bitcoin Address along with WIF Key. Great, now let’s test the code next.

The following content was written by webtricks on February 04, 2020, 05:06:18 PM in the thread How Bitcoin Addresses are generated? Understand the Math behind Bitcoin. All content is owned by the author of the bitcointalk.org post. (original)

TESTING

Code:
This is WIF Key: \${WIF}
This is Uncompressed Public Key: \${uncompressedKey}
This is compressed Public Key: \${compressedKey}
Thisi is hexadecimal of Private Key: \${privateKey}`);

After writing above code in file, save the file and open terminal. Now run the following command in terminal. Make sure, folder is opened in terminal:

node index.js (file name can be different for you)

You will get address, WIF, public keys, private key in terminal and these will match bitaddress generated keys. You can try different private key. Just change the private key in Step 3 and you are good to go.

But let’s not forget the fact that this thread is still for learning purpose. Always use the keys generated by wallets like Electrum and MyCelium, unless you are completely sure what are you doing.

Hope you liked this guide. Do let me know if you still get any doubts, I will address them.

For full code in order, visit: https://webtricks.website/keyGeneration.html

Watch code in action, visit: https://key-generation-by-webby.herokuapp.com/

Editor-in-chief and serial coder & blogger.

Click to comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

# What Everyone Must Know About GPU Crypto Mining

Yes, GPU crypto mining is still profitable. It just depends on which coins you mine.

Published

on

Yes, GPU crypto mining is still profitable. It just depends on which coins you mine. Using the best GPU mining software, you can make a good return on your mining hardware for coins such as Ethereum. The manufacturer and model will clearly affect your choice of GPUs to use. Here are some answers to some of your burning questions about GPU crypto mining.

GPU mining is a process of solving complex maths problems for verifying electronic transactions using computer components. In this case, it utilizes a gaming computer’s graphics processing unit. It doesn’t have to be a gaming computer though and could even be a laptop.

Once a method of mining bitcoins, it has become obsolete several years ago for many different cryptocurrencies that use the Proof-of-Work algorithm. But some people still use it to mine bitcoins and other cryptocurrencies as well.

In the Proof-of-Work model, each miner searches for a hash that is less than a particular value which is called the nonce. The size of the nonce depends on the difficulty value of the cryptocurrency network. Higher difficulties make smaller nonces.

## Will it be profitable?

Every miner asks themselves this question before they purchase large batches of mining gear. That is because GPU mining, like other types of mining, has marginal profits. In other words, you have to be very careful to generate more cryptocurrency than the amount you pay for electricity.

The profits of mining depend a lot on how fast you can find a block. So, if several miners shut down at the same time, the difficulty will be too high to mine blocks. Usually, networks periodically adjust the difficulty based on the number of recently mined blocks.

But it really depends on the quality of your GPU mining software whether you want to stick to GPU or some other powerful device like FPGA.

## The reality of GPU crypto mining these days

Bitcoin mining these days have become very fast paced, and if you don’t have the latest bitcoin miners, then you are going to get left behind.

Application-specific integrated circuit (ASIC) miners took over the Bitcoin mining scene in 2013 causing many miners to switch their obsolete graphics card to script-based altcoins like Dogecoin and Litecoin.

Also in 2018, ASICs predominantly carried out crypto mining of several other coins. And hence mining these coins using GPU or CPU is very hard you are literally competing against large mining pools. Using GPU to mind them hence is pointless and highly unprofitable. Hence there has been a massive shift for miners towards ASIC.

We can say that a single ASIC miner has the equivalent computing power of several hundred GPUs. However, ASICs are non-programmable. That means that you cannot modify them to mine a different cryptocurrency than the one the manufacturer designed them to mine.

But yes, even though the GPU computing power is pretty low, you can still utilize them for mining cryptocurrencies like Ethereum, Zcash, etc. So we can use GPU mining here. But some altcoins weaken the speed of GPUs for crypto mining. For example, Monero uses an algorithm that you cannot optimize for GPUs and ASICs. That is why nobody makes ASICs to mine Monero.

### Can you mine Bitcoin using GPUs?

The answer is NO! Don’t do that, because the major mining pools check for GPU and CPU miners and kick them off the pool to save server resources. Plus, the profits are very tiny and it will take you several years before you mine a good amount of bitcoin, whether using the latest NVIDIA card or something else. Most mining software discourages people to use their GPUs and CPUs for this reason.

We are aware of some altcoin mining pools which claim to pay out in BTC, but these are actually mining a different altcoin and converting it to BTC.

## AMD vs NVIDIA crypto mining

One major advantage of using NVIDIA or AMD GPUs for crypto mining is that they are relatively cheap (compared to ASICs). Hence you can run multiple cards on the same motherboard while mining different cryptocurrencies simultaneously. Miners have long been using Nvidia cards that they have collected at bargains for crypto mining.

Miners are starting to think twice though, as Nvidia began cracking down on GPU crypto mining. They started because miners were buying all the graphics cards that were supposed to be for gamers. Recently, they have lowered the hash rate of the 3060 Ti GPU for Ethereum mining. At the same time, they made a special kind of GPU that you can only use to mine cryptocurrencies such as Ethereum.

We do not know yet if AMD will follow in their footsteps. For now, AMD cards are more suitable for new miners in terms of price as they are the price of almost 2/3rd of the NVIDIA cards. But NVIDIA cards are somewhat more powerful thanks to the CUDA runtime.

## What is the best GPU mining software?

You can choose from Claymore, PhoenixMiner, or Cudo miner. Claymore has long been the king of crypto mining for NVIDIA and AMD cards, but it’s getting a bit old. It was last updated in 2019, and users have reported crashes when running it. Therefore, we do not recommend using Claymore miner anymore.

PhoenixMiner is a newer miner which users have reported success using, and can mine different kinds of algorithms. But users have reported fake copies of PhoenixMiner made by scammers, so stay vigilant. This is the real link to PhoenixMiner.

Cudo miner is software that can control the GPUs in your mining farm. It can mine several different coins and also uses an auto-switcher that always mines the most profitable coin at a given time.

# [GUIDE] How to create an online store and accept Bitcoin by using open-source

I’ve spent the past 15 days writing a very detailed tutorial on how to create an e-commerce store and accept Bitcoin, from scratch, with no coding skills required by using only free and open-source software.

Published

on

The following content was written by Pavle on August 31, 2018, 02:43:53 PM in the thread [GUIDE] How to create an online store and accept Bitcoin by using open-source. All content is owned by the author of the bitcointalk.org post. (original)

I’ve spent the past 15 days writing a very detailed tutorial on how to create an e-commerce store and accept Bitcoin, from scratch, with no coding skills required by using only free and open-source software.

We’ve been running our own bitcoin store for a year now, and wanted to do something for the community and spread the adoption.

The article contains detailed instructions that will guide you through the process step by step.

It’s quite in-depth, there are 10200 words and I also recorded 18 videos to help you along the way.

You can read the article here https://bitcoinshirt.co/how-to-create-store-accept-bitcoin/

And watch the video in an assorted playlist here  https://www.youtube.com/playlist?list=PL7b9Wt9shK2ouN9E-g0viktMMEKFFqelm

Here’s the table of content

1. Under the Hood
1.1Web Hosting
1.1.1Shared Hosting
1.1.2Dedicated Hosting
1.1.3VPS Hosting
1.1.4Why do you need both VPS and Shared for this setup?
1.2Domain name and SSL
1.3WordPress
1.3.1WordPress Theme
1.3.2WordPress Plugins
1.3.2.1Woocommerce
1.3.2.2BTCPay Server
1.4 The cost

2. Web Hosting
2.1Choosing The Hosting Plan
2.2 Domain name
2.3 Setting up the account
2.3.1 Extra Services
2.4 Phone verification
2.5 Creating WordPress and WooCommerce
2.6 E-mail verification (inbox)
2.7 Previewing the website

3.   Customizing WordPress
3.1 Logging into WordPress
3.2 Getting familiar with the back-end interface
3.3 Installing the Theme
3.4 Removing the demo content
3.4.1Removing the plugins
3.4.2Removing the Products
3.4.3Removing product categories

4. Woocommerce Customization
4.1WooCommerce General Settings
4.2 Creating WooCommerce Pages
4.3 Creating product categories
4.4.1 Creating Simple Product
4.4.2 Creating Variation Product
4.5 Shipping rates and methods

5. Installing plugins

6 Customizing Theme
6.2 Customizing Footer
6.2.2 Adding Bitcoin Accepted Here Sign

7. Setting up BTCPay Server
7.1Installing BTCPay WooCommere Plugin
7.2 Connecting to a Third-Party Host
7.2.1 Registering with a third-party host
7.2.2 Pairing your store with a host
7.3 Installing BTCPay self-hosted Server
7.3.2 Creating an account
7.3.3 Creating the Virtual Machine
7.3.3.2 Attaching a volume
7.3.3.3 Enabling CPU usage
7.3.4  DNS Setup
7.3.5 Deploying BTCPay Server
7.4 Connecting BTCPay with your wallet
7.4.1 Connecting your wallet with Ledger Nano S
7.5 Testing BTCPay Checkout

8.Summary
8.1Official documentation
8.3 Free Plugins
8.4 Search Engine Optimization
8.5 Support groups
8.6 Marketing
8.7 Credits
8.8 The stores made by following this tutorial
8.9 Thank you

If you have any feedback, let me know.

If you or someone you know end up with making a store that accepts BTC by following it, please let me know, it would make my day 🙂

# [overview] Recover Bitcoin from any old storage format

The aim of this thread is to give a complete overview for anyone who finds Bitcoins in any storage format.

Published

on

The following content was written by LoyceV on August 26, 2018, 01:09:32 PM in the thread [overview] Recover Bitcoin from any old storage format. All content is owned by the author of the bitcointalk.org post. (original)

[overview] Recover Bitcoin from any old storage format

Background
I’ve seen many threads like: Recovering weird old wallet, and the answer is often very easy if someone recognizes the format.
Since the number of different formats will only grow, and (in the future) I expect more people to forget what format they used to store their Bitcoin 10 or more years ago, I’ve decided to create an overview.
The aim of this thread is to give a complete overview for anyone who finds Bitcoins in any storage format.

Work in progress
This thread is work in progress. Please post any missing storage formats or additional identifying data, so I can add it to the OP (and give you credit). I haven’t tried all possible wallets by myself, and I won’t claim to know all possible formats either. If you find a thread asking about a format not covered yet, please post a link.

Warning: take security precautions
First: make one or more backups (thanks DaveF)! Make sure you’re not working on the only copy you have, as you risk losing everything.
Make sure you know what you’re doing, before doing it! When in doubt, don’t do it.
Ignore or report unsolicited private messages from old or new users. Discuss your needs in public on Bitcointalk, but DO NOT post your private keys, seed phrase words, or wallet files. DO NOT trust “help” you receive by PM, you will get scammed. Be careful which screenshots you upload.
Don’t trust anybody with your private keys, unless you’re absolutely sure you would trust him with the same amount in cash.
Use an air gapped offline computer running from a Linux LIVE DVD (for example Ubuntu or Knoppix) without internet connection when necessary.
Don’t expost large amounts of Bitcoin to a hot wallet. Assume your system is compromised, and act accordingly. Don’t trust your Windows clipboard, malware can change your Bitcoin address to their own, and checking only the first few characters of the address is not enough to prevent this.
If you’re using a paper wallet, you should use the entire balance at once. If you use only a small amount, you risk losing the rest of your balance to a change address.

Before attempting to recover your funds, you should already know where to send them after recovery. Setting up a safe wallet is beyond the scope of this thread, I recommend to start your search here: Choose your [Bitcoin] Wallet. Consider whether or not you want to use a SegWit address.
Create one or more secure backups before funding any wallet.

Bitcoin private keys (this section is largely based on data from bitaddress.org)
• WIF (Wallet Import Format) (51 characters base58, starting with “5”).
Example: 5KMWmYkn5YWkJnUDG4utD9L1HXQv3DBseqqCGsQXmthcEerbA7k
• WIF Compressed (52 characters base58, starting with “K” or “L”).
Note: both WIF and WIF Compressed are derived from the same private key, but result in different Bitcoin addresses.
• Private Key Hexadecimal (64 characters [0-9A-F]) (less common).
Example: CA9A061710B8BC582E1B8BB60D0F3F2751791888AB5C18737620087ABDF74A05
• Private Key (44 characters base64) (less common).
Example: ypoGFxC4vFguG4u2DQ8/J1F5GIirXBhzdiAIer33SgU=
• Mini private key (30 characters base58, starting with “S”, see wiki)
Example: Sf2i92UoH3kMooYXHdDQ4YQvLTdPrQ
• BIP38 password encrypted private key (58 characters base58, starting with “6P”, see bitcoinpaperwallet.com).
Example: 6PRNqE9p5hTUgNy5cxXnrfVKZPX5Qz8sqB7oNfDT9N3YdCM7rqRxruxkN1
• Private key missing checksum
Example: 5KMWmYkn5YWkJnUDG4utD9L1HXQv3DBseqqCGsQXmthcEerbA7k
The last 7 characters of a private key are a checksum. Blockchain.info backups used to omit the checksum. An easy way to restore it, is importing the private key without checksum into a new wallet at blockchain.info (nowadays blockchain.com), and then exporting it again. Note: I do not recommend exposing a private key to an online wallet, but if it was created by Blockchain.info, it should be considered compromised anyway (source and details; this information may be inaccurate (thanks Coding Enthusiast)).
• Private key for SegWit addresses
A private key can be used to create SegWit addresses (starting with “3” or “bc1”). You can import them into Electrum by adding “p2wpkh-p2sh:” or “p2wpkh:” respectively in front of the private key (source and details).
• Incomplete private key
If a few characters of a private key are lost, there are still recovery options (missing 5 character on known locations, missing one character on unknown location (I haven’t tested this)), but further details would go beyond the scope of this thread.
• Blockstack
If you have Bitcoin in a CLI Blockstack node, read this topic and this topic.
If you have the private key, you can choose from many different wallets to import it. Electrum is probably the easiest. If the private key is in the wrong format, you can use bitaddress.org (do this offline!!) to convert it to WIF or WIF Compressed.

Determine wallets based on filenames (note: these are the default filenames, you could have renamed yours)

Seed phrases, Word lists or Mnemonic phrases
Bitcoin wallets can be stored as seed phrases, usually 12 to 24 words long. The used words can be in several languages (thanks HeRetiK).
• 12 words
Example: thrive jump wheel calm eyebrow order ankle raven fee narrow diamond adult
The seed can be extended with one or more custom words.
Use Electrum, or iancoleman’s Mnemonic Code Converter (do this offline!!) to extract all private keys.
• 24 words
Hardware wallets, such as Trezor and Ledger, usually use 24 words.
Example: party describe tunnel brother explain laugh hello have short wood bird desk liar pole neck push wine tooth young mean grain join cheap aisle
Use the original hardware wallet, or iancoleman’s Mnemonic Code Converter (do this offline!!) to extract all private keys.
A common mistake is using the words in the wrong order, where the words are written down like this:
1 2
3 4
5 6
7 8
But you’re trying to recover them like this: 1 3 5 7 …… 2 4 6 8 ……
• Another number of words
If you don’t remember how the list was created, you can use iancoleman’s Mnemonic Code Converter (do this offline!!) to extract all private keys.
• Missing or incorrect word(s)
Try seedrecover.py (I haven’t tested this) (do this offline!!) (thanks o_e_l_e_o)
• Master private key (111 characters, starting with “xprv” (legacy addresses starting with “1”), “yprv” (backward-compatible SegWit addresses starting with “3”) or “zprv” (native SegWit addresses starting with “bc1”) (source).
Example: xprv9xyQEZakyfuyCRGF1moJNatpGDAgMS4hgctAgWU4RNw664qCz6agreZParHx6G24td48SZKnmK8 ppSVMvmyBuTy9L4poDhwgm9aR9GukgQW (source & further reading)
Use Electrum > create new wallet > enter seed.
• Armory Root Key: 18 four letter “words”.
Example (from bitkee.com): eoaj gghu ruaf ghwe jnrh ftuu hweu aeun agkg tudt waja gunn oawg jkwh dhei hjdn itar naoj
Use Armory.
• Blockchain.info: To recover an old legacy Blockchain.info wallet, read this topic and go here.

No wallet?
If you can’t find your wallet.dat, because it’s deleted or renamed, you can try these options (do this offline!!) after you’ve made a backup of the entire partition.

• Pywallet can search for private keys on an entire partition, even when the wallet has been deleted.
• Findwallet can search for a wallet file after it was renamed (but not deleted)

After recovery
For future backups, make sure to keep all information needed to recover your funds.

No spam
All my threads are now self-moderated to stop signature spam. I will remove all irrelevant posts. If you quote the entire OP, your entry will be deleted.
Once in a while I’ll summarize posts and clean up this thread.

Altcoins
This thread and board are meant for Bitcoin only. But, if something comes up, I’ll keep track of methods to restore a damaged private key for altcoins too. For future reference:

Disclaimer
Use this information at your own risk. At all times, think before each action, especially when you’re dealing with private keys. When in doubt, don’t do it!
I’m human, I make mistakes. If something is incorrect, please let me know.

Donations
1MyMoney4uNt5afXALAZpoovJpqojEMkLP (Balance:
)