├── .github └── FUNDING.yml ├── 01_0_Introduction.md ├── 01_1_Introducing_Bitcoin.md ├── 02_0_Setting_Up_a_Bitcoin-Core_VPS.md ├── 02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md ├── 02_2_Setting_Up_Bitcoin_Core_Other.md ├── 03_0_Understanding_Your_Bitcoin_Setup.md ├── 03_1_Verifying_Your_Bitcoin_Setup.md ├── 03_2_Knowing_Your_Bitcoin_Setup.md ├── 03_3_Setting_Up_Your_Wallet.md ├── 03_3__Interlude_Using_Command-Line_Variables.md ├── 03_4_Receiving_a_Transaction.md ├── 03_5_Understanding_the_Descriptor.md ├── 04_0_Sending_Bitcoin_Transactions.md ├── 04_1_Sending_Coins_The_Easy_Way.md ├── 04_2_Creating_a_Raw_Transaction.md ├── 04_2__Interlude_Using_JQ.md ├── 04_3_Creating_a_Raw_Transaction_with_Named_Arguments.md ├── 04_4_Sending_Coins_with_a_Raw_Transaction.md ├── 04_4__Interlude_Using_Curl.md ├── 04_5_Sending_Coins_with_Automated_Raw_Transactions.md ├── 04_6_Creating_a_Segwit_Transaction.md ├── 05_0_Controlling_Bitcoin_Transactions.md ├── 05_1_Watching_for_Stuck_Transactions.md ├── 05_2_Resending_a_Transaction_with_RBF.md ├── 05_3_Funding_a_Transaction_with_CPFP.md ├── 06_0_Expanding_Bitcoin_Transactions_Multisigs.md ├── 06_1_Sending_a_Transaction_to_a_Multisig.md ├── 06_2_Spending_a_Transaction_to_a_Multisig.md ├── 06_3_Sending_an_Automated_Multisig.md ├── 07_0_Expanding_Bitcoin_Transactions_PSBTs.md ├── 07_1_Creating_a_Partially_Signed_Bitcoin_Transaction.md ├── 07_2_Using_a_Partially_Signed_Bitcoin_Transaction.md ├── 07_3_Integrating_with_Hardware_Wallets.md ├── 08_0_Expanding_Bitcoin_Transactions_Other.md ├── 08_1_Sending_a_Transaction_with_a_Locktime.md ├── 08_2_Sending_a_Transaction_with_Data.md ├── 09_0_Introducing_Bitcoin_Scripts.md ├── 09_1_Understanding_the_Foundation_of_Transactions.md ├── 09_2_Running_a_Bitcoin_Script.md ├── 09_3_Testing_a_Bitcoin_Script.md ├── 09_4_Scripting_a_P2PKH.md ├── 09_5_Scripting_a_P2WPKH.md ├── 10_0_Embedding_Bitcoin_Scripts_in_P2SH_Transactions.md ├── 10_1_Understanding_the_Foundation_of_P2SH.md ├── 10_2_Building_the_Structure_of_P2SH.md ├── 10_3_Running_a_Bitcoin_Script_with_P2SH.md ├── 10_4_Scripting_a_Multisig.md ├── 10_5_Scripting_a_Segwit_Script.md ├── 10_6_Spending_a_P2SH_Transaction.md ├── 11_0_Empowering_Timelock_with_Bitcoin_Scripts.md ├── 11_1_Understanding_Timelock_Options.md ├── 11_2_Using_CLTV_in_Scripts.md ├── 11_3_Using_CSV_in_Scripts.md ├── 12_0_Expanding_Bitcoin_Scripts.md ├── 12_1_Using_Script_Conditionals.md ├── 12_2_Using_Other_Script_Commands.md ├── 13_0_Designing_Real_Bitcoin_Scripts.md ├── 13_1_Writing_Puzzle_Scripts.md ├── 13_2_Writing_Complex_Multisig_Scripts.md ├── 13_3_Empowering_Bitcoin_with_Scripts.md ├── 14_0_Using_Tor.md ├── 14_1_Verifying_Your_Tor_Setup.md ├── 14_2_Changing_Your_Bitcoin_Hidden_Services.md ├── 14_3_Adding_SSH_Hidden_Services.md ├── 15_0_Using_i2p.md ├── 15_1_i2p_service.md ├── 16_0_Talking_to_Bitcoind.md ├── 16_1_Accessing_Bitcoind_with_C.md ├── 16_2_Programming_Bitcoind_with_C.md ├── 16_3_Receiving_Bitcoind_Notifications_with_C.md ├── 17_0_Programming_with_Libwally.md ├── 17_1_Setting_Up_Libwally.md ├── 17_2_Using_BIP39_in_Libwally.md ├── 17_3_Using_BIP32_in_Libwally.md ├── 17_4_Using_PSBTs_in_Libwally.md ├── 17_5_Using_Scripts_in_Libwally.md ├── 17_6_Using_Other_Functions_in_Libwally.md ├── 17_7_Integrating_Libwally_and_Bitcoin-CLI.md ├── 18_0_Talking_to_Bitcoind_Other.md ├── 18_1_Accessing_Bitcoind_with_Go.md ├── 18_2_Accessing_Bitcoind_with_Java.md ├── 18_3_Accessing_Bitcoind_with_NodeJS.md ├── 18_4_Accessing_Bitcoind_with_Python.md ├── 18_5_Accessing_Bitcoind_with_Rust.md ├── 18_6_Accessing_Bitcoind_with_Swift.md ├── 19_0_Understanding_Your_Lightning_Setup.md ├── 19_1_Verifying_Your_Lightning_Setup.md ├── 19_2_Knowing_Your_lightning_Setup.md ├── 19_2__Interlude_Accessing_a_Second_Lightning_Node.md ├── 19_3_Setting_Up_a_Channel.md ├── 20_0_Using_Lightning.md ├── 20_1_Generate_a_Payment_Request.md ├── 20_2_Paying_a_Invoice.md ├── 20_3_Closing_a_Channel.md ├── 20_4_Lightning_Network_Review.md ├── A0_Appendices.md ├── A1_0_Understanding_Bitcoin_Standup.md ├── A2_0_Compiling_Bitcoin_from_Source.md ├── A3_0_Using_Bitcoin_Regtest.md ├── CLA-signed ├── CLA.ChristopherA.F8D36C91357405ED.asc ├── CLA.HGRAMS.AED496548E2F3810CCAB.asc ├── CLA.gorazdko.41F0EA1699A74C1E2FA41B538CF96BC3FF9DBBCE.asc ├── CLA.icculp.C076C96C1110EA901974F2324CE131ACA12429CC.asc ├── CLA.javiervargas.703D8DF52A3510C3A8E6AA5DCBDD67C74A547004.asc ├── CLA.joa-rodrigues.90487FE3801DE403173A2EDBC685E6D937FDC203.asc ├── CLA.jodobear.EE060B4A9AED976B7CBDB3A03A9C7E8730284351.asc ├── CLA.lukedevj.AB4609E35FB50FA1CA970EB1CF23EC813BBF.asc ├── CLA.maxcrowar.993F06969AB6603D1EEE890D4A6533DB95D4E166.asc ├── CLA.namcios.55A24BE0AEE5DB4152C6A4108E3A368317269AB4.asc ├── CLA.shannona.7EC6B928606F27AD.asc └── CLA.srahalh.F3A6CF9EFEEE0D4908CD72D44613300262C7313C.asc.txt ├── CLA.md ├── CONTRIBUTING.md ├── Chapter_word_counts.ipynb ├── Chapter_word_counts.md ├── LICENSE-CC-BY-4.0.md ├── README.md ├── TODO-20.md ├── TODO-23.md ├── TODO-30.md ├── TRANSLATING.md ├── bitcoin.conf-annotated.txt ├── es ├── 01_0_Introduccion.md ├── 01_1_Introduciendo_Bitcoin.md ├── 02_0_Configurando_un_Bitcoin-Core_VPS.md ├── 02_1_Configurando_un_Bitcoin-Core_VPS_con_StackScript.md ├── 02_2_Configurando_Bitcoin_Core_Otros.md ├── 03_0_Entendiendo_Su_Configuracion_Bitcoin.md ├── 03_1_Verificando_Su_Configuracion_Bitcoin.md ├── 03_2_Conociendo_Su_Configuracion_Bitcoin.md ├── 03_3_Configurando_Su_Billetera.md ├── 03_3_Interludio_Usando_Variables_Linea_Comando.md ├── 03_4_Recibiendo_una_Transaccion.md ├── 03_5_Entendiendo_El_Descriptor.md ├── 04_0_Enviando_Transacciones_Bitcoin.md ├── 04_1_Enviando_Monedas_de_la_Forma_Facil.md ├── 04_2_Creando_una_Transaccion_Cruda.md ├── 04_2_Interludio_Usando_JQ.md ├── 04_3_Creando_una_Transaccion_Cruda_con_Argumentos_Ingresados_con_Nombre.md ├── 04_4_Enviando_Monedas_con_una_Transaccion_Cruda.md ├── 04_4_Interludio_Usando_Curl.md ├── 04_5_Enviando_Monedas_con_Transacciones_Crudas_Automatizadas.md ├── 04_6_Creando_una_Transaccion_Segwit.md ├── 05_0_Controlando_Transacciones_Bitcoin.md ├── 05_1_Vigilando_por_Transacciones_Estancadas.md ├── 05_2_Reenviando_a_Transaccion_con_RBF.md ├── 05_3_Financiando_una_Transaccion_con_CPFP.md ├── 06_0_Expandiendo_las_Transacciones_Bitcoin_con_Multifirmas.md ├── 06_1_Enviando_una_Transaccion_a_una_Direccion_Multifirma.md ├── 06_2_Gastando_una_Transaccion_con_una_Direccion_Multifirma.md ├── 06_3_Enviando_una_Multifirma_Automatizada.md ├── 07_0_Expandiendo_las_Transacciones_Bitcoin_con_PSBTs.md ├── 07_1_Creando_una_Transaccion_Bitcoin_Parcialmente_Firmada.md ├── 07_2_Usando_una_Transaccion_Bitcoin_Parcialmente_Firmada.md ├── 07_3_Integrando_con_Hardware_Wallets.md ├── 08_0_Expandiendo_Bitcoin_Transacciones_Otros.md ├── 08_1_Enviando_una_Transaccion_con_Bloqueo_de_Tiempo.md ├── 08_2_Enviando_una_Transaccion_con_Datos.md ├── 09_0_Introduciendo_Bitcoin_Scripts.md ├── 09_1_Entendiendo_la_Base_de_las_Transacciones.md ├── 09_2_Ejecutando_un_Script_Bitcoin.md ├── 09_3_Probando_un_Script_Bitcoin.md ├── 09_4_Codificando_una_P2PKH.md ├── 09_5_Codificando_una_P2WPKH.md ├── 10_0_Embebiendo_Bitcoin_Scripts_en_Transacciones_P2SH.md ├── 10_1_Entendiendo_la_Base_de_P2SH.md ├── 10_2_Construyendo_la_Estructura_de_P2SH.md ├── 10_3_Ejecutando_un_Script_Bitcoin_con_P2SH.md ├── 10_4_Codificando_una_Multifirma.md ├── 10_5_Codificando_un_Script_Segwit.md ├── 10_6_Gastando_una_Transaccion_P2SH.md ├── 11_0_Potenciando_Bloqueos_de_Tiempo_con_Bitcoin_Scripts.md ├── 11_1_Entendiendo_las_Opciones_de_los_Bloqueos_de_Tiempo.md ├── 11_2_Usando_CLTV_en_Scripts.md ├── 11_3_Usando_CSV_en_Scripts.md ├── 12_0_Expandiendo_Scripts_Bitcoin.md ├── 12_1_Usando_Script_Condicionales.md ├── 12_2_Usando_Otros_Comandos_de_Scripting.md ├── 13_0_Disenando_Bitcoin_Scripts_Reales.md ├── 13_1_Escribiendo_Puzzle_Scripts.md ├── 13_2_Escribiendo_Scripts_Multifirma_Complejos.md ├── 13_3_Potenciando_Bitcoin_con_Scripts.md ├── 14_0_Usando_Tor.md ├── 14_1_Verificando_Su_Configuracion_Tor.md ├── 14_2_Cambiando_Sus_Servicios_Bitcoin_Ocultos.md ├── 14_3_Agregando_Servicios_SSH_Ocultos.md ├── 15_0_Usando_i2p.md ├── 15_1_Servicio_i2p.md ├── 16_0_Hablando_a_Bitcoind_con_C.md ├── 16_1_Accediendo_a_Bitcoind_en_C_con_las_Bibliotecas_RPC.md ├── 16_2_Programando_Bitcoind_en_C_con_las_Bibliotecas_RPC.md ├── 16_3_Recibiendo_Notificaciones_de_Bitcoind_en_C_con_las_Bibliotecas_ZMQ.md ├── 17_0_Programando_Bitcoin_con_Libwally.md ├── 17_1_Configurando_Libwally.md ├── 17_2_Usando_BIP39_en_Libwally.md ├── 17_3_Usando_BIP32_en_Libwally.md ├── 17_4_Usando_PSBTs_en_Libwally.md ├── 17_5_Usando_Scripts_en_Libwally.md ├── 17_6_Usando_Otras_Funciones_en_Libwally.md ├── 17_7_Integrando_Libwally_y_Bitcoin-CLI.md ├── 18_0_Hablando_a_Bitcoind_con_Otros_Lenguajes.md ├── 18_1_Accediendo_a_Bitcoind_con_Go.md ├── 18_2_Accediendo_a_Bitcoind_con_Java.md ├── 18_3_Accediendo_a_Bitcoind_con_NodeJS.md ├── 18_4_Accediendo_a_Bitcoind_con_Python.md ├── 18_5_Accediendo_a_Bitcoind_con_Rust.md ├── 18_6_Accediendo_a_Bitcoind_con_Swift.md ├── 19_0_Entendiendo_Su_Configuracion_Lightning.md ├── 19_1_Verificando_Su_Configuracion_Lightning.md ├── 19_2_Conociendo_Su_Configuracion_Lightning.md ├── 19_2_Interludio_Accediendo_a_un_Segundo_Nodo_Lightning.md ├── 19_3_Creando_un_Canal_en_Lightning.md ├── 20_0_Usando_Lightning.md ├── 20_1_Generando_una_Solicitud_de_Pago.md ├── 20_2_Pagando_una_Factura.md ├── 20_3_Cerrando_un_Canal_Lightning.md ├── 20_4_Expandiendo_la_Red_Lightning.md ├── A0_Apendices.md ├── A1_0_Entendiendo_Bitcoin_Standup.md ├── A2_0_Compilando_Bitcoin_desde_la_Fuente.md ├── A3_0_Usando_Bitcoin_Regtest.md └── README.md ├── images ├── README.md ├── logos │ ├── README.md │ ├── lbtc-logo-black.ai │ ├── lbtc-logo-black.jpg │ ├── lbtc-logo-black.png │ ├── lbtc-logo-white.ai │ ├── lbtc-screen.jpg │ ├── lbtc-screen.png │ └── lbtc-screen.psd ├── psbt-roles-for-cli-1.png ├── psbt-roles-for-cli-2.png ├── psbt-roles-for-cli-3.png └── psbt.png ├── pt ├── 01_0_Introduction.md ├── 01_1_Introducing_Bitcoin.md ├── 02_0_Setting_Up_a_Bitcoin-Core_VPS.md ├── 02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md ├── 02_2_Setting_Up_Bitcoin_Core_Other.md ├── 03_0_Understanding_Your_Bitcoin_Setup.md ├── 03_1_Verifying_Your_Bitcoin_Setup.md ├── 03_2_Knowing_Your_Bitcoin_Setup.md ├── 03_3_Setting_Up_Your_Wallet.md ├── 03_3__Interlude_Using_Command-Line_Variables.md ├── 03_4_Receiving_a_Transaction.md ├── 03_5_Understanding_the_Descriptor.md ├── 04_0_Sending_Bitcoin_Transactions.md ├── 04_1_Sending_Coins_The_Easy_Way.md ├── 04_2_Creating_a_Raw_Transaction.md ├── 04_2__Interlude_Using_JQ.md ├── 04_3_Creating_a_Raw_Transaction_with_Named_Arguments.md ├── 04_4_Sending_Coins_with_a_Raw_Transaction.md ├── 04_4__Interlude_Using_Curl.md ├── 04_5_Sending_Coins_with_Automated_Raw_Transactions.md ├── 04_6_Creating_a_Segwit_Transaction.md ├── 05_0_Controlling_Bitcoin_Transactions.md ├── 05_1_Watching_for_Stuck_Transactions.md ├── 05_2_Resending_a_Transaction_with_RBF.md ├── 05_3_Funding_a_Transaction_with_CPFP.md ├── 06_0_Expanding_Bitcoin_Transactions_Multisigs.md ├── 06_1_Sending_a_Transaction_to_a_Multisig.md ├── 06_2_Spending_a_Transaction_to_a_Multisig.md ├── 06_3_Sending_an_Automated_Multisig.md ├── 07_0_Expanding_Bitcoin_Transactions_PSBTs.md ├── 07_1_Creating_a_Partially_Signed_Bitcoin_Transaction.md ├── 07_2_Using_a_Partially_Signed_Bitcoin_Transaction.md ├── 07_3_Integrating_with_Hardware_Wallets.md ├── 08_0_Expanding_Bitcoin_Transactions_Other.md ├── 08_1_Sending_a_Transaction_with_a_Locktime.md ├── 08_2_Sending_a_Transaction_with_Data.md ├── 09_0_Introducing_Bitcoin_Scripts.md ├── 09_1_Understanding_the_Foundation_of_Transactions.md ├── 09_2_Running_a_Bitcoin_Script.md ├── 09_3_Testing_a_Bitcoin_Script.md ├── 09_4_Scripting_a_P2PKH.md ├── 09_5_Scripting_a_P2WPKH.md ├── 10_0_Embedding_Bitcoin_Scripts_in_P2SH_Transactions.md ├── 10_1_Understanding_the_Foundation_of_P2SH.md ├── 10_2_Building_the_Structure_of_P2SH.md ├── 10_3_Running_a_Bitcoin_Script_with_P2SH.md ├── 10_4_Scripting_a_Multisig.md ├── 10_5_Scripting_a_Segwit_Script.md ├── 10_6_Spending_a_P2SH_Transaction.md ├── 11_0_Empowering_Timelock_with_Bitcoin_Scripts.md ├── 11_1_Understanding_Timelock_Options.md ├── 11_2_Using_CLTV_in_Scripts.md ├── 11_3_Using_CSV_in_Scripts.md ├── 12_0_Expanding_Bitcoin_Scripts.md ├── 12_1_Using_Script_Conditionals.md ├── 12_2_Using_Other_Script_Commands.md ├── 13_0_Designing_Real_Bitcoin_Scripts.md ├── 13_1_Writing_Puzzle_Scripts.md ├── 13_2_Writing_Complex_Multisig_Scripts.md ├── 13_3_Empowering_Bitcoin_with_Scripts.md ├── 14_0_Using_Tor.md ├── 14_1_Verifying_Your_Tor_Setup.md ├── 14_2_Changing_Your_Bitcoin_Hidden_Services.md ├── 14_3_Adding_SSH_Hidden_Services.md ├── 15_0_Using_i2p.md ├── 15_1_i2p_service.md ├── 16_0_Talking_to_Bitcoind.md ├── 16_1_Accessing_Bitcoind_with_C.md ├── 16_2_Programming_Bitcoind_with_C.md ├── 16_3_Receiving_Bitcoind_Notifications_with_C.md ├── 17_0_Programming_with_Libwally.md ├── 17_1_Setting_Up_Libwally.md ├── 17_2_Using_BIP39_in_Libwally.md ├── 17_3_Using_BIP32_in_Libwally.md ├── 17_4_Using_PSBTs_in_Libwally.md ├── 17_5_Using_Scripts_in_Libwally.md ├── 17_6_Using_Other_Functions_in_Libwally.md ├── 17_7_Integrating_Libwally_and_Bitcoin-CLI.md ├── 18_0_Talking_to_Bitcoind_Other.md ├── 18_1_Accessing_Bitcoind_with_Go.md ├── 18_2_Accessing_Bitcoind_with_Java.md ├── 18_3_Accessing_Bitcoind_with_NodeJS.md ├── 18_4_Accessing_Bitcoind_with_Python.md ├── 18_5_Accessing_Bitcoind_with_Rust.md ├── 18_6_Accessing_Bitcoind_with_Swift.md ├── 19_0_Understanding_Your_Lightning_Setup.md ├── 19_1_Verifying_Your_Lightning_Setup.md ├── 19_2_Knowing_Your_lightning_Setup.md ├── 19_2__Interlude_Accessing_a_Second_Lightning_Node.md ├── 19_3_Setting_Up_a_Channel.md ├── 20_0_Using_Lightning.md ├── 20_1_Generate_a_Payment_Request.md ├── 20_2_Paying_a_Invoice.md ├── 20_3_Closing_a_Channel.md ├── 20_4_Lightning_Network_Review.md ├── A0_Appendices.md ├── A1_0_Understanding_Bitcoin_Standup.md ├── A2_0_Compiling_Bitcoin_from_Source.md ├── A3_0_Using_Bitcoin_Regtest.md ├── CONTRIBUTING.md └── README.md ├── public ├── LBftCLI-compiling_bitcoin-db4.png └── LBftCLI-compiling_bitcoin-git.png ├── signed-cla ├── CLA.KoreaComK.F2BD6AD8C042ED6E9C5A232F3B909765FBEA7B30.asc ├── CLA.csralvall.8DEF166DA59D7898.asc └── CLA.lukedevj.AB4609E35FB50FA1CA970EB1CF23EC813BBF.asc └── src ├── 04_2_i_txfee-calc.sh ├── 10_2_integer2lehex.sh ├── 16_1_getmininginfo.c ├── 16_1_testbitcoin.c ├── 16_2_sendtoaddress.c ├── 16_3_chainlistener.c ├── 17_1_testwally.c ├── 17_2_genmnemonic.c ├── 17_3_genhd.c ├── 17_4_createemptypsbt.c ├── 17_4_examinepsbt.c ├── 17_5_replacewithscript.c ├── 17_7_genhd_for_import.c ├── 18_1_blockinfo.go ├── 18_1_getaddress.go ├── 18_1_getamountreceived.go ├── 18_1_getbalance.go ├── 18_1_lookuptransaction.go ├── 18_1_sendtransaction.go ├── 18_2_App-getinfo.java ├── 18_2_App-listen.java ├── 18_2_App-sendtx.java ├── 18_3_getinfo.js ├── 18_3_sendtx.js ├── 18_3_walletinfo.js ├── 18_4_getinfo.py ├── 18_4_sendtx.py ├── 18_4_walletinfo.py ├── 18_5_main-getinfo.rs ├── 18_5_main-sendtx.rs ├── 18_6_getinfo.playground └── 18_6_sendtx.playground /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: ChristopherA 4 | custom: https://btcpay.blockchaincommons.com 5 | -------------------------------------------------------------------------------- /02_0_Setting_Up_a_Bitcoin-Core_VPS.md: -------------------------------------------------------------------------------- 1 | # Chapter Two: Creating a Bitcoin-Core VPS 2 | 3 | To get started with Bitcoin, you first need to set up a machine running Bitcoin. The articles in this chapter describe how to do so, primarily by using a VPS (Virtual Private Server). 4 | 5 | ## Objectives for this Chapter 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Decide Between the Five Major Types of Bitcoin Nodes 10 | * Create a Bitcoin Node for Development 11 | * Create a Local Instance of the Bitcoin Blockchain 12 | 13 | Supporting objectives include the ability to: 14 | 15 | * Understand the Basic Network Setup of the VPS 16 | * Decide Which Security Priorities to Implement 17 | * Understand the Difference between Pruned and Unpruned Nodes 18 | * Understand the Difference between Mainnet, Testnet, and Regtest Nodes 19 | * Interpret the Basics of the Bitcoin Configuration File 20 | 21 | ## Table of Contents 22 | 23 | You don't actually need to read this entire chapter. Decide if you want to run a StackScript to set a node up on a Linode VPS (§2.2); or you want to set up on a different environment, such as on an AWS machine or a Mac (§2.3). Then, jump to the appropriate section. Additional information on our suggested setups may also be found in [Appendix I](A1_0_Understanding_Bitcoin_Standup.md). 24 | 25 | * [Section One: Setting Up a Bitcoin Core VPS with Bitcoin Standup](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md) 26 | * [Section Two: Setting Up a Bitcoin Core Machine via Other Means](02_2_Setting_Up_Bitcoin_Core_Other.md) 27 | -------------------------------------------------------------------------------- /02_2_Setting_Up_Bitcoin_Core_Other.md: -------------------------------------------------------------------------------- 1 | # 2.2: Setting Up a Bitcoin-Core Machine via Other Means 2 | 3 | The previous section, [§2.1: Setting Up a Bitcoin-Core VPS with Bitcoin Standup](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md), presumed that you would be creating a full node on a VPS using a Linode Stackscript. However, you can actually create a Bitcoin-Core instance via any methodology of your choice and still follow along with the later steps of this tutorial. 4 | 5 | Following are other setup methodologies that we are aware of: 6 | 7 | * *[Compiling from Source](A2_0_Compiling_Bitcoin_from_Source.md).* If you prefer to compile Bitcoin Core by hand, that's covered in Appendix 2. 8 | * *[Using GordianServer-macOS](https://github.com/BlockchainCommons/GordianServer-macOS).* If you have a modern Mac, you can use Blockchain Commons' *GordianNode* app, powered by *BitcoinStandup*, to install a full node on your Mac. 9 | * *[Using Other Bitcoin Standup Scripts](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts).* Blockchain Commons also offers a version of the Linode script that you used that can be run from the command line on any Debian or Ubuntu machine. This tends to be the leading-edge script, which means that it's more likely to feature new functions, like Lightning installation. 10 | * *[Setting Up a Bitcoin Node on AWS](https://wolfmcnally.com/115/developer-notes-setting-up-a-bitcoin-node-on-aws/).* @wolfmcnally has written a step-by-step tutorial for setting up Bitcoin-Core with Amazon Web Services (AWS). 11 | * *[Setting Up a Bitcoin Node on a Raspberry Pi 3](https://medium.com/@meeDamian/bitcoin-full-node-on-rbp3-revised-88bb7c8ef1d1).* Damian Mee explains how to set up a headless full node on a Raspberry Pi 3. 12 | 13 | Be sure that you are installing on a current version of your OS, to avoid problems down the line. As of this writing, this course is tested on Debian 11. 14 | 15 | ## What's Next? 16 | 17 | Unless you want to return to one of the other methodologies for creating a Bitcoin-Core node, you should: 18 | 19 | * Move on to "bitcoin-cli" with [Chapter Three: Understanding Your Bitcoin Setup](03_0_Understanding_Your_Bitcoin_Setup.md). 20 | -------------------------------------------------------------------------------- /03_0_Understanding_Your_Bitcoin_Setup.md: -------------------------------------------------------------------------------- 1 | # Chapter Three: Understanding Your Bitcoin Setup 2 | 3 | You're now ready to begin working with the `bitcoin-cli` command-line interface. But that first requires that you understand your Bitcoin setup and its wallet features, which is what will be explained in this chapter. 4 | 5 | For this and future chapters, we presume that you have a VPS with Bitcoin installed, running `bitcoind`. We also presume that you are connected to testnet, allowing for access to bitcoins without using real funds. You can either do this with Bitcoin Standup at Linode.com, per [§2.1: Setting up a Bitcoin-Core VPS with Bitcoin Standup](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md), or via other means, per [§2.2: Setting up a Bitcoin-Core Machine via Other Means](02_2_Setting_Up_Bitcoin_Core_Other.md). 6 | 7 | ## Objectives for This Chapter 8 | 9 | After working through this chapter, a developer will be able to: 10 | 11 | * Demonstrate that Their Bitcoin Node is Installed and Up-to-date 12 | * Create an Address to Receive Bitcoin Funds 13 | * Use Basic Wallet Commands 14 | * Create an Address from a Descriptor 15 | 16 | Supporting objectives include the ability to: 17 | 18 | * Understand the Basic Bitcoin File Layout 19 | * Use Basic Informational Commands 20 | * Understand What a Bitcoin Address Is 21 | * Understand What a Wallet Is 22 | * Understand How to Import Addresses 23 | 24 | ## Table of Contents 25 | 26 | * [Section One: Verifying Your Bitcoin Setup](03_1_Verifying_Your_Bitcoin_Setup.md) 27 | * [Section Two: Knowing Your Bitcoin Setup](03_2_Knowing_Your_Bitcoin_Setup.md) 28 | * [Section Three: Setting Up Your Wallet](03_3_Setting_Up_Your_Wallet.md) 29 | * [Interlude: Using Command-Line Variables](03_3__Interlude_Using_Command-Line_Variables.md) 30 | * [Section Four: Receiving a Transaction](03_4_Receiving_a_Transaction.md) 31 | * [Section Five: Understanding the Descriptor](03_5_Understanding_the_Descriptor.md) 32 | -------------------------------------------------------------------------------- /03_3__Interlude_Using_Command-Line_Variables.md: -------------------------------------------------------------------------------- 1 | # Interlude: Using Command-Line Variables 2 | 3 | The previous section demonstrated a number of command-line commands used without obfuscation or interference. However, that's often not the best way to run Bitcoin from the command line. Because you're dealing with long, complex, and unreadable variables, it's easy to make a mistake if you're copying those variables around (or, satoshi forfend, if you're typing them in by hand). Because those variables can mean the difference between receiving and losing real money, you don't _want_ to make mistakes. For these reasons, we strongly suggest using command-line variables to save addresses, signatures, or other long strings of information whenever it's reasonable to do so. 4 | 5 | If you're using `bash`, you can save information to a variable like this: 6 | ``` 7 | $ VARIABLE=$(command) 8 | ``` 9 | That's a simple command substitution, the equivalent to ``VARIABLE=`command` ``. The command inside the parentheses is run, then assigned to the VARIABLE. 10 | 11 | To create a new address would then look like this: 12 | ``` 13 | $ unset NEW_ADDRESS_1 14 | $ NEW_ADDRESS_1=$(bitcoin-cli getnewaddress "" legacy) 15 | ``` 16 | These commands clear the NEW_ADDRESS_1 variable, just to be sure, then fill it with the results of the `bitcoin-cli getnewaddress` command. 17 | 18 | You can then use your shell's `echo` command to look at your (new) address: 19 | ``` 20 | $ echo $NEW_ADDRESS_1 21 | mi25UrzHnvn3bpEfFCNqJhPWJn5b77a5NE 22 | ``` 23 | Because you have your address in a variable, you can now easily sign a message for that address, without worrying about mistyping the address. You'll of course save that signature into a variable too! 24 | ``` 25 | $ NEW_SIG_1=$(bitcoin-cli signmessage $NEW_ADDRESS_1 "Hello, World") 26 | $ echo $NEW_SIG_1 27 | IPYIzgj+Rg4bxDwCyoPiFiNNcxWHYxgVcklhmN8aB2XRRJqV731Xu9XkfZ6oxj+QGCRmTe80X81EpXtmGUpXOM4= 28 | ``` 29 | The rest of this tutorial will use this style of saving information to variables when it's practical. 30 | 31 | > :book: ***When is it not practical to use command-line variables?*** Command-line variables aren't practical if you need to use the information somewhere other than on the command line. For example, saving your signature may not actually be useful if you're just going to have to send it to someone else in an email. In addition, some future commands will output JSON objects instead of simple information, and variables can't be used to capture that information ... at least not without a _little_ more work. 32 | 33 | ## Summary: Using Command-Line Variables 34 | 35 | Shell variables can be used to hold long Bitcoin strings, minimizing the chances of mistakes. 36 | 37 | ## What's Next? 38 | 39 | Continue "Understanding Your Bitcoin Setup" with [§3.4: Receiving a Transaction](03_4_Receiving_a_Transaction.md). 40 | -------------------------------------------------------------------------------- /04_0_Sending_Bitcoin_Transactions.md: -------------------------------------------------------------------------------- 1 | # Chapter Four: Sending Bitcoin Transactions 2 | 3 | This chapter describes three different methods for sending bitcoins to normal P2PKH addresses from the command line, using only the bitcoin-cli interface. 4 | 5 | ## Objectives for This Chapter 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Decide How to Send Money Through Bitcoin 10 | * Create a Raw Transaction 11 | * Use Arithmetic to Calculate Fees 12 | 13 | Supporting objectives include the ability to: 14 | 15 | * Understand Transactions & Transaction Fees 16 | * Understand Legacy & SegWit Transactions 17 | * Use Basic Methods to Send Money 18 | * Use Auto Fee Calculation Methods to Send Money 19 | * Understand the Dangers of Raw Transactions 20 | 21 | ## Table of Contents 22 | 23 | * [Section One: Sending Coins the Easy Way](04_1_Sending_Coins_The_Easy_Way.md) 24 | * [Section Two: Creating a Raw Transaction](04_2_Creating_a_Raw_Transaction.md) 25 | * [Interlude: Using JQ](04_2__Interlude_Using_JQ.md) 26 | * [Section Three: Creating a Raw Transaction with Named Arguments](04_3_Creating_a_Raw_Transaction_with_Named_Arguments.md) 27 | * [Section Four: Sending Coins with Raw Transactions](04_4_Sending_Coins_with_a_Raw_Transaction.md) 28 | * [Interlude: Using Curl](04_4__Interlude_Using_Curl.md) 29 | * [Section Five: Sending Coins with Automated Raw Transactions](04_5_Sending_Coins_with_Automated_Raw_Transactions.md) 30 | * [Section Six: Creating a SegWit Transaction](04_6_Creating_a_Segwit_Transaction.md) 31 | -------------------------------------------------------------------------------- /05_0_Controlling_Bitcoin_Transactions.md: -------------------------------------------------------------------------------- 1 | # Chapter Five: Controlling Bitcoin Transactions 2 | 3 | Sending a transaction isn't always the end of the story. Using the RBF (replace-by-fee) and CPFP (child-pays-for-parent) protocols, a developer can continue to control the transaction after it's been sent, to improve efficiency or to recover transactions that get stuck. These methods will begin to spotlight the true power of Bitcoin. 4 | 5 | ## Objectives for This Section 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Decide Whether RBF or CPFP Might Help a Transaction 10 | * Create Replacement Transaction Using RBF 11 | * Create New Transactions Using CPFP 12 | 13 | Supporting objectives include the ability to: 14 | 15 | * Understand the Mempool 16 | * Understand the Difference Between RBF and CPFP 17 | * Plan for the Power of RBF 18 | 19 | ## Table of Contents 20 | 21 | * [Section One: Watching for Stuck Transactions](05_1_Watching_for_Stuck_Transactions.md) 22 | * [Section Two: Resending a Transaction with RBF](05_2_Resending_a_Transaction_with_RBF.md) 23 | * [Section Three: Funding a Transaction with CPFP](05_3_Funding_a_Transaction_with_CPFP.md) 24 | -------------------------------------------------------------------------------- /06_0_Expanding_Bitcoin_Transactions_Multisigs.md: -------------------------------------------------------------------------------- 1 | # Chapter Six: Expanding Bitcoin Transactions with Multisigs 2 | 3 | Basic bitcoin transactions: (1) send funds; (2) to a single P2PKH or SegWit recipient; (3) from a single machine; (4) immediately. However, all four parts of this definition can be expanded using more complex Bitcoin transactions. This first chapter on "Expansion" shows how to vary points (2) and (3) by sending money to an address that represents multiple recipients (or at least, multiple signers). 4 | 5 | ## Objectives for This Section 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Create Multisignature Bitcoin Addresses Using Bitcoin Fundamentals 10 | * Create Multisignature Bitcoin Addresses Using Easier Mechanisms 11 | 12 | Supporting objectives include the ability to: 13 | 14 | * Understand How to Spend Funds Sent to a Multisignature 15 | * Plan for the Power of Multisignatures 16 | 17 | ## Table of Contents 18 | 19 | * [Section One: Sending a Transaction with a Multsig](06_1_Sending_a_Transaction_to_a_Multisig.md) 20 | * [Section Two: Spending a Transaction with a Multsig](06_2_Spending_a_Transaction_to_a_Multisig.md) 21 | * [Section Three: Sending & Spending an Automated Multisig](06_3_Sending_an_Automated_Multisig.md) 22 | -------------------------------------------------------------------------------- /07_0_Expanding_Bitcoin_Transactions_PSBTs.md: -------------------------------------------------------------------------------- 1 | # Chapter Seven: Expanding Bitcoin Transactions with PSBTs 2 | 3 | The previous chapter discussed how to use multisigs to collaboratively determine consent among multiple parties. It's not the only way to collaborate in the creation of Bitcoin transactions. PSBTs are a much newer technology that allow you to collaborate at a variety of stages, including the creation, funding, and authentication of a Bitcoin transaction. 4 | 5 | ## Objectives for This Section 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Create Transactions with PSBTs 10 | * Use Command Line Tools to Complete PSBTs 11 | * Use HWI to Interact with a Hardware Wallet 12 | 13 | Supporting objectives include the ability to: 14 | 15 | * Understand How PSBTs Differ from Multisignatures 16 | * Understand the Full Workflow of Working with PSBTs 17 | * Plan for the Power of PSBTs 18 | * Understand The Use of a Hardware Wallet 19 | 20 | ## Table of Contents 21 | 22 | * [Section One: Creating a Partially Signed Bitcoin Transaction](07_1_Creating_a_Partially_Signed_Bitcoin_Transaction.md) 23 | * [Section Two: Using a Partially Signed Bitcoin Transaction](07_2_Using_a_Partially_Signed_Bitcoin_Transaction.md) 24 | * [Section Three: Integrating with Hardware Wallets](07_3_Integrating_with_Hardware_Wallets.md) 25 | 26 | -------------------------------------------------------------------------------- /08_0_Expanding_Bitcoin_Transactions_Other.md: -------------------------------------------------------------------------------- 1 | # Chapter Eight: Expanding Bitcoin Transactions in Other Ways 2 | 3 | The definition of basic transactions back in [Chapter Six](06_0_Expanding_Bitcoin_Transactions_Multisigs.md) said that they sent _funds_ _immediately_, but those are both elements that can be changed. This final section on Expanding Bitcoin Transactions talks about how to send things other than cash and how to do it at a time other than now. 4 | 5 | ## Objectives for This Section 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Create Transactions with Locktimes 10 | * Create Transactions with Data 11 | 12 | Supporting objectives include the ability to: 13 | 14 | * Understand the Different Sorts of Timelocks 15 | * Plan for the Power of Locktime 16 | * Plan for the Power of OP_RETURN 17 | 18 | ## Table of Contents 19 | 20 | * [Section One: Sending a Transaction with a Locktime](08_1_Sending_a_Transaction_with_a_Locktime.md) 21 | * [Section Two: Sending a Transaction with Data](08_2_Sending_a_Transaction_with_Data.md) 22 | -------------------------------------------------------------------------------- /09_0_Introducing_Bitcoin_Scripts.md: -------------------------------------------------------------------------------- 1 | # Chapter 9: Introducing Bitcoin Scripts 2 | 3 | To date, we've been interacting with Bitcoin at a relatively high level of abstraction. The `bitcoin-cli` program offers access to a variety of RPC commands that support the creation and control of raw Bitcoin transactions that include funds, data, timelocks, and multisigs. 4 | 5 | However, Bitcoin offers much more complexity than that. It includes a simple scripting language that can be used to create even more complex redemption conditions. If multisigs and timelocks provided the basis of Smart Contracts, then Bitcoin Script builds high on that foundation. It's the next step in empowering Bitcoin. 6 | 7 | ## Objectives for This Chapter 8 | 9 | After working through this chapter, a developer will be able to: 10 | 11 | * Design a Bitcoin Script 12 | * Apply a Bitcoin Script 13 | 14 | Supporting objectives include the ability to: 15 | 16 | * Understand the Purpose of Bitcoin Scripts 17 | * Understand the P2PKH Script 18 | * Understand How P2WPKH Works with Scripting 19 | * Understand the Needs for Bitcoin Script Testing 20 | 21 | ## Table of Contents 22 | 23 | * [Section One: Understanding the Foundation of Transactions](09_1_Understanding_the_Foundation_of_Transactions.md) 24 | * [Section Two: Running a Bitcoin Script](09_2_Running_a_Bitcoin_Script.md) 25 | * [Section Three: Testing a Bitcoin Script](09_3_Testing_a_Bitcoin_Script.md) 26 | * [Section Four: Scripting a P2PKH](09_4_Scripting_a_P2PKH.md) 27 | * [Section Five: Scripting a P2WPKH](09_5_Scripting_a_P2WPKH.md) 28 | -------------------------------------------------------------------------------- /10_0_Embedding_Bitcoin_Scripts_in_P2SH_Transactions.md: -------------------------------------------------------------------------------- 1 | # Chapter 10: Embedding Bitcoin Scripts in P2SH Transactions 2 | 3 | Bitcoin Script moves down several levels of abstraction, allowing you to minutely control the redemption conditions of Bitcoin funds. But, how do you actually incorporate those Bitcoin Scripts into the transactions you've been building to date? The answer is a new sort of Bitcoin transaction, the P2SH. 4 | 5 | ## Objectives for This Chapter 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Design a P2SH Transaction 10 | * Apply a P2SH Bitcoin Script 11 | 12 | Supporting objectives include the ability to: 13 | 14 | * Understand the P2SH Script 15 | * Understand the Multisig Script 16 | * Understand the Various Segwit Variations of Scripts 17 | * Understand How to Spend Funds Sent to a P2SH 18 | 19 | ## Table of Contents 20 | 21 | * [Section One: Understanding the Foundation of P2SH](10_1_Understanding_the_Foundation_of_P2SH.md) 22 | * [Section Two: Building the Structure of P2SH](10_2_Building_the_Structure_of_P2SH.md) 23 | * [Section Three: Running a Bitcoin Script with P2SH](10_3_Running_a_Bitcoin_Script_with_P2SH.md) 24 | * [Section Four: Scripting a Multisig](10_4_Scripting_a_Multisig.md) 25 | * [Section Five: Scripting a Segwit Script](10_5_Scripting_a_Segwit_Script.md) 26 | * [Section Six: Spending a P2SH Transaction](10_6_Spending_a_P2SH_Transaction.md) 27 | -------------------------------------------------------------------------------- /10_3_Running_a_Bitcoin_Script_with_P2SH.md: -------------------------------------------------------------------------------- 1 | # 10.3: Running a Bitcoin Script with P2SH 2 | 3 | Now that you know the theory and practice behind P2SH addresses, you're ready to turn a non-standard Bitcoin Script into an actual transaction. We'll be reusing the simple locking script from [§9.2: Running a Bitcoin Script](09_2_Running_a_Bitcoin_Script.md), `OP_ADD 99 OP_EQUAL`. 4 | 5 | ## Create a P2SH Transaction 6 | 7 | To lock a transaction with this Script, do the following: 8 | 9 | 1. Serialize `OP_ADD 99 OP_EQUAL`: 10 | 1. OP_ADD = 0x93 — a simple opcode translation 11 | 2. 99 = 0x01, 0x63 — this opcode pushes one byte onto the stack, 99 (hex: 0x63) 12 | * No worries about endian conversion because it's only one byte 13 | 3. OP_EQUAL = 0x87 — a simple opcode translation 14 | 4. `` = "93016387" 15 | 16 | ``` 17 | $ btcc OP_ADD 99 OP_EQUAL 18 | 93016387 19 | ``` 20 | 21 | 2. Save `` for future reference as the `redeemScript`. 22 | 1. `` = "93016387" 23 | 3. SHA-256 and RIPEMD-160 hash the serialized script. 24 | 1. `` = "3f58b4f7b14847a9083694b9b3b52a4cea2569ed" 25 | 4. Produce a P2SH locking script that includes the ``. 26 | 1. `scriptPubKey` = "a9143f58b4f7b14847a9083694b9b3b52a4cea2569ed87" 27 | 28 | You can then create a transaction using this `scriptPubKey`, probably via an API. 29 | 30 | ## Unlock the P2SH Transaction 31 | 32 | To unlock this transaction requires that the recipient produce a `scriptSig` that prepends two constants totalling ninety-nine to the serialized script: `1 98 `. 33 | 34 | ### Run the First Round of Validation 35 | 36 | The process of unlocking the P2SH transaction then begins with a first round of validation, which checks that the redeem script matches the hashed value in the locking script. 37 | 38 | Concatenate `scriptSig` and `scriptPubKey` and execute them, as normal: 39 | ``` 40 | Script: 1 98 OP_HASH160 OP_EQUAL 41 | Stack: [] 42 | 43 | Script: 98 OP_HASH160 OP_EQUAL 44 | Stack: [ 1 ] 45 | 46 | Script: OP_HASH160 OP_EQUAL 47 | Stack: [ 1 98 ] 48 | 49 | Script: OP_HASH160 OP_EQUAL 50 | Stack: [ 1 98 ] 51 | 52 | Script: OP_EQUAL 53 | Running: OP_HASH160 54 | Stack: [ 1 98 ] 55 | 56 | Script: OP_EQUAL 57 | Stack: [ 1 98 ] 58 | 59 | Script: 60 | Running: OP_EQUAL 61 | Stack: [ 1 98 True ] 62 | ``` 63 | The Script ends with a `True` on top of the stack, and so it succeeds ... even though there's other cruft below it. 64 | 65 | However, because this was a P2SH script, the execution isn't done. 66 | 67 | ### Run the Second Round of Validation 68 | 69 | For the second round of validation, verify that the values in the unlocking script satisfy the `redeemScript`: deserialize the `redeemScript` ("93016387" = "OP_ADD 99 OP_EQUAL"), then execute it using the items in the `scriptSig` prior to the serialized script: 70 | 71 | ``` 72 | Script: 1 98 OP_ADD 99 OP_EQUAL 73 | Stack: [ ] 74 | 75 | Script: 98 OP_ADD 99 OP_EQUAL 76 | Stack: [ 1 ] 77 | 78 | Script: OP_ADD 99 OP_EQUAL 79 | Stack: [ 1 98 ] 80 | 81 | Script: 99 OP_EQUAL 82 | Running: 1 98 OP_ADD 83 | Stack: [ 99 ] 84 | 85 | Script: OP_EQUAL 86 | Stack: [ 99 99 ] 87 | 88 | Script: 89 | Running: 99 99 OP_EQUAL 90 | Stack: [ True ] 91 | ``` 92 | With that second validation _also_ true, the UTXO can now be spent! 93 | 94 | ## Summary: Building a Bitcoin Script with P2SH 95 | 96 | Once you know the technique of building P2SHes, any Script can be embedded in a Bitcoin transaction; and once you understand the technique of validating P2SHes, it's easy to run the scripts in two rounds. 97 | 98 | ## What's Next? 99 | 100 | Continue "Embedding Bitcoin Scripts" with [§10.4: Scripting a Multisig](10_4_Scripting_a_Multisig.md). 101 | -------------------------------------------------------------------------------- /10_6_Spending_a_P2SH_Transaction.md: -------------------------------------------------------------------------------- 1 | # 10.6: Spending a P2SH Transaction 2 | 3 | Before we close out this overview of P2SH transactions, we're going to touch upon how to spend them. This section is mainly an overview, referring back to a previous section where we _already_ spent a P2SH transaction. 4 | 5 | ## Use the Redeem Script 6 | 7 | As we saw in [§6.2: Spending a Transaction with a Multisig](06_2_Spending_a_Transaction_to_a_Multisig.md), spending a P2SH transaction is all about having that serialized version of the locking script, the so-called _redeemScript_. So, the first step in being able to spend a P2SH transaction is making sure that you save the _redeemScript_ before you give out the P2SH address to everyone. 8 | 9 | ### Collect Your Variables 10 | 11 | Because P2SH addresses other than the special multisig and nested Segwit addresses aren't integrated into `bitcoin-cli` there will be no short-cuts for P2SH spending like you saw in [§6.3: Sending an Automated Multisig](06_3_Sending_an_Automated_Multisig.md). You're going to need to collect all the more complex variables on your own! 12 | 13 | This means that you need to collect: 14 | 15 | * The `hex` of the `scriptPubKey` for the transaction you're spending 16 | * The serialized `redeemScript` 17 | * Any private keys, since you'll be signing by hand 18 | * All of the regular `txids`, `vouts`, and `addresses` that you'd need 19 | 20 | ## Create the Transaction 21 | 22 | As we saw in §6.2, the creation of a transaction is pretty standard: 23 | ``` 24 | $ rawtxhex=$(bitcoin-cli -named createrawtransaction inputs='''[ { "txid": "'$utxo_txid'", "vout": '$utxo_vout' } ]''' outputs='''{ "'$recipient'": 0.00005}''') 25 | $ echo $rawtxhex 26 | 020000000121654fa95d5a268abf96427e3292baed6c9f6d16ed9e80511070f954883864b10000000000ffffffff0188130000000000001600142c48d3401f6abed74f52df3f795c644b4398844600000000 27 | ``` 28 | However, signing requires entering extra information for the (1) `scriptPubKey`; (2) the `redeemScript`; and (3) any required private keys. 29 | 30 | Here's the example of doing so for that P2SH-embedded multisig in §6.2: 31 | ``` 32 | $ bitcoin-cli -named signrawtransactionwithkey hexstring=$rawtxhex prevtxs='''[ { "txid": "'$utxo_txid'", "vout": '$utxo_vout', "scriptPubKey": "'$utxo_spk'", "redeemScript": "'$redeem_script'" } ]''' privkeys='["cNPhhGjatADfhLD5gLfrR2JZKDE99Mn26NCbERsvnr24B3PcSbtR"]' 33 | ``` 34 | With any other sort of P2SH you're going to be including a different `redeemscript`, but otherwise the practice is exactly the same. The only difference is that after two chapters of work on Scripts you now understand what the `scriptPubKey` is and what the `redeemScript` is, so hopefully what were mysterious elements four chapters ago are now old hat. 35 | 36 | ## Summary: Spending a P2SH Transaction 37 | 38 | You already spent a P2SH back in Chapter 6, when you resent a multsig transaction the hard way, which required lining up the `scriptPubKey` and `redeemScript` information. Now you know that the `scriptPubKey` is a standardized P2SH locking script, while the `redeemScript` matches a hash in that locking script and that you need to be able to run it with the proper variables to receive a `True` result. But other than knowing more, there's nothing new in spending a P2SH transaction, because you already did it! 39 | 40 | ## What's Next? 41 | 42 | Advance through "Bitcoin Scripting" with [Chapter Eleven: Empowering Timelock with Bitcoin Scripts](11_0_Empowering_Timelock_with_Bitcoin_Scripts.md). 43 | -------------------------------------------------------------------------------- /11_0_Empowering_Timelock_with_Bitcoin_Scripts.md: -------------------------------------------------------------------------------- 1 | # Chapter 11: Empowering Timelock with Bitcoin Scripts 2 | 3 | The `nLockTime` feature from [§8.1](08_1_Sending_a_Transaction_with_a_Locktime.md) was just the beginning of Timelocks. When you start writing Bitcoin Scripts, two timelocking opcodes become available. 4 | 5 | ## Objectives for This Chapter 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Decide which Timelock to Use 10 | * Create Scripts with CLTV 11 | * Create Scripts with CSV 12 | 13 | Supporting objectives include the ability to: 14 | 15 | * Understand the Differences Between the Different Timelocks 16 | * Generate Relative Times 17 | 18 | ## Table of Contents 19 | 20 | * [Section One: Understanding Timelock Options](11_1_Understanding_Timelock_Options.md) 21 | * [Section Two: Using CLTV in Scripts](11_2_Using_CLTV_in_Scripts.md) 22 | * [Section Three: Using CSV in Scripts](11_3_Using_CSV_in_Scripts.md) 23 | 24 | -------------------------------------------------------------------------------- /11_1_Understanding_Timelock_Options.md: -------------------------------------------------------------------------------- 1 | # 11.1: Understanding Timelock Options 2 | 3 | In [§8.1: Sending a Transaction with a Locktime](08_1_Sending_a_Transaction_with_a_Locktime.md), `nLocktime` offered a great first option for locking transactions so that they couldn't be spent until some point in the future — based either on time or blockheight. But, that's not the only way to put a timelock on a transaction. 4 | 5 | ## Understand the Limitations of nLockTime 6 | 7 | `nLockTime` is a simple and powerful way to lock a transaction, but it has some limitations: 8 | 9 | 1. **No Divisions.** `nLocktime` locks the entire transaction. 10 | 2. **No Networking.** Most modern nodes won't accept a `nLockTime` into the mempool until it's almost ready to finalize. 11 | 3. **No Scripts.** The original, simple use of `nLockTime` didn't allow it to be used in Scripts. 12 | 4. **No Protection.** `nLockTime` allows the funds to be spent with a different, non-locked transaction. 13 | 14 | The last item was often the dealbreaker for `nLockTime`. It prevented a transaction from being spent, but it didn't prevent the funds from being used in a different transaction. So, it had uses, but they all depended on trust. 15 | 16 | ## Understand the Possibilities of Timelock Scripts 17 | 18 | In more recent years, Bitcoin Core has expanded to allow the manipulation of timelocks at the opcode level with _OP_CHECKLOCKTIMEVERIFY_ (CLTV) and _OP_CHECKSEQUENCEVERIFY_ (CSV). These both work under a new methodology that further empowers Bitcoin. 19 | 20 | _They Are Opcodes._ Because they're opcodes, CLTV and CSV can be used as part of more complex redemption conditions. Most often they're linked with the conditionals described in the next chapter. 21 | 22 | _They Lock Outputs._ Because they're opcodes that are included in transactions as part of a `sigPubKey`, they just lock that single output. That means that the transactions are accepted onto the Bitcoin network and that the UTXOs used to fund those transactions are spent. There's no going back on a transaction timelocked with CLTV or CSV like there is with a bare `nLockTime`. Respending the resultant UTXO then requires that the timelock conditions be met. 23 | 24 | Here's one catch for using timelocks: _They're one-way locks._ Timelocks are designed so that they unlock funds at a certain time. They cannot then relock a fund: once a timelocked fund is available to spend, it remains available to spend. 25 | 26 | ### Understand the Possibilities of CLTV 27 | 28 | _OP_CHECKLOCKTIMEVERIFY_ or CLTV is a match for the classic `nLockTime` feature, but in the new opcode-based paradigm. It allows a UTXO to become accessible at a certain time or at a certain blockheight. 29 | 30 | CLTV was first detailed in [BIP 65](https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki). 31 | 32 | ### Understand the Possibilities of CSV 33 | 34 | _OP_CHECKSEQUENCEVERIFY_ or CSV depends on a new sort of "relative locktime", which is set in the transaction's _nSequence_ field. As usual, it can be set as either a time or a blockheight. If it's set as a time, "n", then a relative-timelocked transaction is spendable "n x 512" seconds after its UTXO was mined, and if it's set as a block, "n", then a relative-timelocked transaction is spendable "n" blocks after its UTXO was mined. 35 | 36 | The use of `nSequence` for a relative timelock was first detailed in [BIP 68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki), then the CSV opcode was added in [BIP 112](https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki). 37 | 38 | ## Summary: Understanding Timelock Options 39 | 40 | You now have four options for Timelock: 41 | 42 | * `nLockTime` to keep a transaction off the blockchain until a specific time. 43 | * `nSequence` to keep a transaction off the blockchain until a relative time. 44 | * CLTV to make a UTXO unspendable until a specific time. 45 | * CSV to make a UTXO unspendable until a relative time. 46 | 47 | ## What's Next? 48 | 49 | Continue "Empowering Timelock" with [§11.2: Using CLTV in Scripts](11_2_Using_CLTV_in_Scripts.md). 50 | -------------------------------------------------------------------------------- /12_0_Expanding_Bitcoin_Scripts.md: -------------------------------------------------------------------------------- 1 | # Chapter 12: Expanding Bitcoin Scripts 2 | 3 | There's still a little more to Bitcoin Scripts. Conditionals give you full access to flow control, while a variety of other opcodes can expand your possibilities. 4 | 5 | ## Objectives for This Chapter 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Decide How to Use Script Conditionals 10 | * Decide How to Use Other Script Opcodes 11 | 12 | Supporting objectives include the ability to: 13 | 14 | * Understand the Full Range of Scripting Possibilities 15 | * Identify How to Learn More about Opcodes 16 | 17 | ## Table of Contents 18 | 19 | * [Section One: Using Script Conditionals](12_1_Using_Script_Conditionals.md) 20 | * [Section Two: Using Other Script Commands](12_2_Using_Other_Script_Commands.md) 21 | -------------------------------------------------------------------------------- /12_2_Using_Other_Script_Commands.md: -------------------------------------------------------------------------------- 1 | # 12.2: Using Other Script Commands 2 | 3 | You may already have in hand most of the Bitcoin Script opcodes that you'll be using in most scripts. However, Bitcoin Script offers a lot more options, which might be exactly what you need to create the financial instrument of your dreams. 4 | 5 | You should consult the [Bitcoin Script page](https://en.bitcoin.it/wiki/Script) for a more thorough look at all of these and many other commands. This section only highlights the most notable opcodes. 6 | 7 | ## Understand Arithmetic Opcodes 8 | 9 | Arithmetic opcodes manipulate or test numbers. 10 | 11 | Manipulate one number: 12 | 13 | * OP_1ADD (0x8b) — Increment by one 14 | * OP_1SUB (0x8c) — Decrement by one 15 | * OP_NEGATE (0x8f) — Flip the sign of the number 16 | * OP_ABS (0x90) — Make the number positive 17 | * OP_NOT (0x91) — Flips 1 and 0, else 0 18 | 19 | Also see: `OP_0NOTEQUAL` (0x92) 20 | 21 | Manipulate two numbers mathematically: 22 | 23 | * OP_ADD (0x93) — Add two numbers 24 | * OP_SUB (0x94) — Subtract two numbers 25 | * OP_MIN (0xa3) — Return the smaller of two numbers 26 | * OP_MAX (0xa4) — Return the larger of two numbers 27 | 28 | Manipulate two numbers logically: 29 | 30 | * OP_BOOLAND (0x9a) — 1 if both numbers are not 0, else 0 31 | * OP_BOOLOR (0x9b) — 1 if either number is not 0, else 0 32 | 33 | Test two numbers: 34 | 35 | * OP_NUMEQUAL (0x9c) — 1 if both numbers are equal, else 0 36 | * OP_LESSTHAN (0x9f) — 1 if first number is less than second, else 0 37 | * OP_GREATERTHAN (0xa0) — 1 if first number is greater than second, else 0 38 | * OP_LESSTHANOREQUAL (0xa1) — 1 if first number is less than or equal to second, else 0 39 | * OP_GREATERTHANOREQUAL (0xa2) — 1 if first number is greater than or equal to second, else 0 40 | 41 | Also see: `OP_NUMEQUALVERIFY` (0x9d), `OP_NUMNOTEQUAL` (0x9e) 42 | 43 | Test three numbers: 44 | 45 | * OP_WITHIN (0xa5) — 1 if a number is in the range of two other numbers 46 | 47 | ## Understand Stack Opcodes 48 | 49 | There are a shocking number of stack opcodes, but other than `OP_DROP`, `OP_DUP`, and sometimes `OP_SWAP` they're generally not necessary if you're careful about stack ordering. Nonetheless, here are a few of the more interesting ones: 50 | 51 | * OP_DEPTH (0x74) — Pushes the size of the stack 52 | * OP_DROP (0x75) — Pops the top stack item 53 | * OP_DUP (0x76) — Duplicates the top stack item 54 | * OP_PICK (0x79) — Duplicates the nth stack item as the top of the stack 55 | * OP_ROLL (0x7a) — Moves the nth stack item to the top of the stack 56 | * OP_SWAP (0x7c) — Swaps the top two stack items 57 | 58 | Also see: `OP_TOALTSTACK` (0x6b), `OP_FROMALTSTACK` (0x6c), `OP_2DROP` (0x6d), `OP_2DUP` (0x6e), `OP_3DUP` (0x6f), `OP_2OVER` (0x70), `OP_2ROT` (0x71), `OP_2SWAP` (0x72), `OP_IFDUP` (0x73), `OP_NIP` (0x77), `OP_OVER` (0x78), `OP_ROT` (0x7b), and `OP_TUCK` (0x7d). 59 | 60 | ## Understand Cryptographic Opcodes 61 | 62 | Finally, a variety of opcodes support hashing and signature checking: 63 | 64 | Hash: 65 | 66 | * OP_RIPEMD160 (0xa6) — RIPEMD-160 67 | * OP_SHA1 (0xa7) — SHA-1 68 | * OP_SHA256 (0xa8) - SHA-256 69 | * OP_HASH160 (0xa9) — SHA-256 + RIPEMD-160 70 | * OP_HASH256 (0xaa) — SHA-256 + SHA-256 71 | 72 | Check Signatures: 73 | 74 | * OP_CHECKSIG (0xac) — Check a signature 75 | * OP_CHECKMULTISIG (0xae) — Check a m-of-n multisig 76 | 77 | Also see: `OP_CODESEPARATOR` (0xab), `OP_CHECKSIGVERIFY` (0xad), and `OP_CHECKMULTISIGVERIFY` (0xaf). 78 | 79 | ## Summary: Using Other Script Commands 80 | 81 | Bitcoin Script includes a wide array of arithemetic, stack, and cryptographic opcodes. Most of these additional opcodes are probably not as common as the ones discussed in previous sections, but nonetheless they're available if they're just what you need to write your Script! 82 | 83 | ## What's Next? 84 | 85 | Advance through "Bitcoin Scripting" with [Chapter Thirteen: Designing Real Bitcoin Scripts](13_0_Designing_Real_Bitcoin_Scripts.md). 86 | -------------------------------------------------------------------------------- /13_0_Designing_Real_Bitcoin_Scripts.md: -------------------------------------------------------------------------------- 1 | # Chapter 13: Designing Real Bitcoin Scripts 2 | 3 | Our Bitcoin Scripts to date have been largely theoretical examples, because we've still been putting together the puzzle pieces. Now, with the full Bitcoin Script repetoire in hand, we're ready to dig into several real-world Bitcoin Scripts and see how they work. 4 | 5 | ## Objectives for This Chapter 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Assess Real-World Bitcoin Scripts 10 | * Create Real-World Bitcoin Scripts 11 | 12 | Supporting objectives include the ability to: 13 | 14 | * Understand Existing Bitcoin Scripts 15 | * Understand the Importance of Signatures 16 | 17 | ## Table of Contents 18 | 19 | * [Section One: Writing Puzzles Scripts](13_1_Writing_Puzzle_Scripts.md) 20 | * [Section Two: Writing Complex Multisig Scripts](13_2_Writing_Complex_Multisig_Scripts.md) 21 | * [Section Three: Empowering Bitcoin with Scripts](13_3_Empowering_Bitcoin_with_Scripts.md) 22 | -------------------------------------------------------------------------------- /14_0_Using_Tor.md: -------------------------------------------------------------------------------- 1 | # Chapter 14: Using Tor 2 | 3 | Tor is one of the standard programs installed by [Bitcoin Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts). It will help to keep your server secure, which is critically important when you're dealing with cryptocurrency. This chapter digresses momentarily from Bitcoin to help you understand this core security infrastructure. 4 | 5 | ## Objectives for This Chapter 6 | 7 | After working through this chapter, a developer will be able to: 8 | 9 | * Use a Tor Setup 10 | * Perform Tor Maintenance 11 | 12 | Supporting objectives include the ability to: 13 | 14 | * Understand the Tor Network 15 | * Understand Bitcoin's Various Ports 16 | 17 | ## Table of Contents 18 | 19 | * [Section One: Verifying Your Tor Setup](14_1_Verifying_Your_Tor_Setup.md) 20 | * [Section Two: Changing Your Bitcoin Hidden Services](14_2_Changing_Your_Bitcoin_Hidden_Services.md) 21 | * [Section Three: Adding SSH Hidden Services](14_3_Adding_SSH_Hidden_Services.md) 22 | -------------------------------------------------------------------------------- /14_2_Changing_Your_Bitcoin_Hidden_Services.md: -------------------------------------------------------------------------------- 1 | # Chapter 14.2: Changing Your Bitcoin Hidden Services 2 | 3 | > :information_source: **NOTE:** This section has been recently added to the course and is an early draft that may still be awaiting review. Caveat reader. 4 | 5 | You've got a working Tor service, but over time you may wish to reset or otherwise adjust it. 6 | 7 | ## Secure Your Hidden Services 8 | 9 | Tor allows you to limit which clients talk to your hidden services. If you did not already authorize your client during your server setup, at the earliest opportunity you should do the following: 10 | 11 | 1. Request your Tor V3 Authentication Public Key from your client. (In [GordianWallet](https://github.com/BlockchainCommons/GordianWallet-iOS), it's available under the settings menu.) 12 | 2. Go to the appropriate subdirectory for your Bitcoin hidden service, which if you used Bitcoin Standup is `/var/lib/tor/standup/`. 13 | 3. Go to the `authorized_clients` subdirectory. 14 | 4. Add a file called `[anything].auth`. The `[anything]` can really be anything. 15 | 5. Place the public key (and nothing else) in the file. 16 | 17 | Once you've added an `.auth` file to the `authorized_client` subdirectory, then only authorized clients will be able to communicate with that hidden service. You can add ~330 different public keys to enable different clients. 18 | 19 | ## Reset Your `bitcoind` Onion Address 20 | 21 | If you ever want to reset your onion address for `bitcoind`, just remove the `onion_private_key` in your data directory, such as `~/.bitcoin/testnet`: 22 | ``` 23 | $ cd ~/.bitcoin/testnet 24 | $ rm onion_private_key 25 | ``` 26 | When you restart, a new onion address will be generated: 27 | ``` 28 | 2020-07-22T23:52:27Z tor: Got service ID pyrtqyiqbwb3rhe7, advertising service pyrtqyiqbwb3rhe7.onion:18333 29 | 2020-07-22T23:52:27Z tor: Cached service private key to /home/standup/.bitcoin/testnet3/onion_private_key 30 | ``` 31 | 32 | ## Reset Your RPC Onion Address 33 | 34 | If you want to reset your onion address for RPC access, you similarly delete the appropriate `HiddenServiceDirectory` and restart Tor: 35 | ``` 36 | $ sudo rm -rf /var/lib/tor/standup/ 37 | $ sudo /etc/init.d/tor restart 38 | ``` 39 | 40 | > :warning: **WARNING:** Reseting your RPC onion address will disconnect any mobile wallets or other services that you've connected using the Quicklink API. Do this with extreme caution. 41 | 42 | ## Force `bitcoind` to Use Tor 43 | 44 | Finally, you can force `bitcoind` to use onion by adding the following to your `bitcoin.conf`: 45 | ``` 46 | proxy=127.0.0.1:9050 47 | listen=1 48 | bind=127.0.0.1 49 | onlynet=onion 50 | ``` 51 | You will then need to add onion-based seed nodes or other nodes to your setup, once more by editing the `bitcoin.conf`: 52 | ``` 53 | seednode=address.onion 54 | seednode=address.onion 55 | seednode=address.onion 56 | seednode=address.onion 57 | addnode=address.onion 58 | addnode=address.onion 59 | addnode=address.onion 60 | addnode=address.onion 61 | ``` 62 | See [Bitcoin Onion Nodes](https://github.com/emmanuelrosa/bitcoin-onion-nodes) for a listing and an example of how to add them. 63 | 64 | Afterward, restart `tor` and `bitcoind`. 65 | 66 | You should now be communicating exlusively on Tor. But, unless you are in a hostile state, this level of anonymity is probably not required. It also is not particularly recommended: you might greatly decrease your number of potential peers, inviting problems of censorship or even correlation. You may also see lag. And, this setup may give you a false sense of anonymity that really doesn't exist on the Bitcoin network. 67 | 68 | > :warning: **WARNING:** This setup is untested! Use at your own risk! 69 | 70 | ## Summary: Changing Your Bitcoin Hidden Services 71 | 72 | You probably won't need to fool with your Onion services once you've verified them, but in case you do, here's how to reset a Tor address that has become compromised or to move over to exclusive-Tor use for your `bitcoind`. 73 | 74 | ## What's Next? 75 | 76 | Continue "Understanding Tor" with [14.3: Adding SSH Hidden Services](14_3_Adding_SSH_Hidden_Services.md). 77 | -------------------------------------------------------------------------------- /14_3_Adding_SSH_Hidden_Services.md: -------------------------------------------------------------------------------- 1 | # Chapter 14.3: Adding SSH Hidden Services 2 | 3 | > :information_source: **NOTE:** This section has been recently added to the course and is an early draft that may still be awaiting review. Caveat reader. 4 | 5 | To date, you've used Tor with your Bitcoin services, but you can also use it to protect other services on your machine, improving their security and privacy. This section demonstrates how by introducing an `ssh` hidden service to login remotely using Tor. 6 | 7 | ## Create SSH Hidden Services 8 | 9 | New services are created by adding them to the `/etc/tor/torrc` file: 10 | ``` 11 | $ su 12 | # cat >> /etc/tor/torrc << EOF 13 | HiddenServiceDir /var/lib/tor/hidden-service-ssh/ 14 | HiddenServicePort 22 127.0.0.1:22 15 | EOF 16 | # exit 17 | ``` 18 | Here's what that means: 19 | 20 | * HiddenServiceDir: Indicates that you have a hidden service directory with the necessary configuration at this path. 21 | * HiddenServicePort: Indicates the tor port to be used; in the case of SSH, this is usually 22. 22 | 23 | After you add the appropriate lines to your `torrc` file, you will need to restart Tor: 24 | ``` 25 | $ sudo /etc/init.d/tor restart 26 | ``` 27 | 28 | After the restart, your `HiddenServiceDir` should have new files as follows: 29 | ``` 30 | $ sudo ls -l /var/lib/tor/hidden-service-ssh 31 | total 16 32 | drwx--S--- 2 debian-tor debian-tor 4096 Jul 22 14:55 authorized_clients 33 | -rw------- 1 debian-tor debian-tor 63 Jul 22 14:56 hostname 34 | -rw------- 1 debian-tor debian-tor 64 Jul 22 14:55 hs_ed25519_public_key 35 | -rw------- 1 debian-tor debian-tor 96 Jul 22 14:55 hs_ed25519_secret_key 36 | ``` 37 | The file `hostname` in this directory contains your new onion ID: 38 | ``` 39 | $ sudo cat /var/lib/tor/hidden-service-ssh/hostname 40 | qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion 41 | ``` 42 | You can connect to the `ssh` hidden service using `torify` and that address: 43 | ``` 44 | $ torify ssh standup@qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion 45 | The authenticity of host 'qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion (127.42.42.0)' can't be established. 46 | ECDSA key fingerprint is SHA256:LQiWMtM8qD4Nv7eYT1XwBPDq8fztQafEJ5nfpNdDtCU. 47 | Are you sure you want to continue connecting (yes/no)? yes 48 | Warning: Permanently added 'qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion' (ECDSA) to the list of known hosts. 49 | standup@qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion's password: 50 | ``` 51 | ## Summary: Adding SSH Hidden Services 52 | 53 | Now that you've got Tor installed and know how to use it, you can add other services to Tor. You just add lines to your `torrc` (on your server), then connect with `torify` (on your client). 54 | 55 | > :fire: ***What's the power of Other Hidden Services?*** Every time you access a service on your server remotely, you leave footprints on the network. Even if the data is encrypted by something like SSH (or TLS), lurkers on the network can see where you're connecting from, where you're connecting to, and what service you're using. Does this matter? This is the question you have to ask. But if the answer is "Yes", you can protect the connection with a hidden service. 56 | 57 | ## What's Next? 58 | 59 | For a different sort of privacy, move on to "Using i2p" with [Chapter Fifteen: Using i2p](15_0_Using_i2p.md). 60 | -------------------------------------------------------------------------------- /15_0_Using_i2p.md: -------------------------------------------------------------------------------- 1 | # Chapter 15: Using I2P 2 | 3 | There are alternatives to Tor. One is the Invisible Internet Project (I2P), a fully encrypted private network layer. It uses a distributed [network database](https://geti2p.net/en/docs/how/network-database) and encrypted unidirectional tunnels between peers. The biggest difference between Tor and I2P is that Tor is fundamentally a proxy network that offers internet services in a private form, while I2P is fundamentally a sequestered network that offers I2P services only to the I2P network, creating a "network within a network". However, you might just want it as an alternative, so that you're not dependent solely on Tor. 4 | 5 | I2P is not currently installed by [Bitcoin Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts), as I2P support was recently added in Bitcoin Core. However, this chapter explains how to manually install it. 6 | 7 | ## Objectives for This Chapter 8 | 9 | After working through this chapter, a developer will be able to: 10 | 11 | * Run Bitcoin Core as an I2P (Invisible Internet Project) service 12 | 13 | Supporting objectives include the ability to: 14 | 15 | * Understand the I2P Network 16 | * Learn the difference between Tor and I2P 17 | 18 | ## Table of Contents 19 | 20 | * [Section One: Bitcoin Core as an I2P (Invisible Internet Project) service](15_1_i2p_service.md) 21 | -------------------------------------------------------------------------------- /16_0_Talking_to_Bitcoind.md: -------------------------------------------------------------------------------- 1 | # Chapter 16: Talking to Bitcoind with C 2 | 3 | While working with Bitcoin Scripts, we hit the boundaries of what's possible with `bitcoin-cli`: it can't currently be used to generate transactions containing unusual scripts. Shell scripts also aren't great for some things, such as creating listener programs that are constantly polling. Fortunately, there are other ways to access the Bitcoin network: programming APIs. 4 | 5 | This section focuses on three different libraries that can be used as the foundation of sophisticated C programming: an RPC library and a JSON library together allow you to recreate a lot of what you did in shell scripts, but now using C; while a ZMQ library links you in to notifications, something you haven't been able to previously access. (The next chapter will cover an even more sophisticated library called Libwally, to finish out this introductory look at programming Bitcoin with C.) 6 | 7 | ## Objectives for This Chapter 8 | 9 | After working through this chapter, a developer will be able to: 10 | 11 | * Create C Programs that use RPC to Talk to the Bitcoind 12 | * Create C Programs that use ZMQ to Talk to the Bitcoind 13 | 14 | Supporting objectives include the ability to: 15 | 16 | * Understand how to use an RPC library 17 | * Understand how to use a JSON library 18 | * Understand the capabilities of ZMQ 19 | * Understand how to use a ZMQ library 20 | 21 | ## Table of Contents 22 | 23 | * [Section One: Accessing Bitcoind in C with RPC Libraries](16_1_Accessing_Bitcoind_with_C.md) 24 | * [Section Two: Programming Bitcoind in C with RPC Libraries](16_2_Programming_Bitcoind_with_C.md) 25 | * [Section Three: Receiving Notifications in C with ZMQ Libraries](16_3_Receiving_Bitcoind_Notifications_with_C.md) 26 | -------------------------------------------------------------------------------- /17_0_Programming_with_Libwally.md: -------------------------------------------------------------------------------- 1 | # Chapter 17: Programming with Libwally 2 | 3 | The previous chapter presented three C Libraries, for RPC, JSON, and ZMQ, all of which are intended to interact directly with `bitcoind`, just like you've been doing since the start. But, sometimes you might want to code without direct access to a `bitcoind`. This might be due to an offline client, or just because you want to keep some functionality internal to your C program. You also might want to get into deeper wallet functionality, like mnemonic word creation or address derivation. That's where Libwally comes in: it's a wallet library for C, C++, Java, NodeJS, or Python, with wrappers also available for other languages, such as Swift. 4 | 5 | This chapter touches upon the functionality possible within Libwally, most of which complements the work you've done through RPC access to `bitcoind`, but some of which replicates it. It also shows how to integrate that work with the RPC clients that you're more familiar with. However, note that this is just the barest introduction to Libwally. Several of its more important function sets are highlighted, but we never do more than stick our toes in. If you find its functions useful or intriguing, then you'll need to dig in much more deeply than this course can cover. 6 | 7 | ## Objectives for This Chapter 8 | 9 | After working through this chapter, a developer will be able to: 10 | 11 | * Use Wallet Functions with Libwally 12 | * Perform Manipulations of PSBTs and Transactions with Libwally 13 | * Implement Designs that Mix Libwally and RPC Work 14 | 15 | Supporting objectives include the ability to: 16 | 17 | * Understand BIP39 Mnemonic Words 18 | * Understand More about BIP32 Hierarchical Wallets 19 | * Summarize the Functional Depth of Libwally 20 | 21 | ## Table of Contents 22 | 23 | * [Section One: Setting Up Libwally](17_1_Setting_Up_Libwally.md) 24 | * [Section Two: Using BIP39 in Libwally](17_2_Using_BIP39_in_Libwally.md) 25 | * [Section Three: Using BIP32 in Libwally](17_3_Using_BIP32_in_Libwally.md) 26 | * [Section Four: Using PSBTs in Libwally](17_4_Using_PSBTs_in_Libwally.md) 27 | * [Section Five: Using Scripts in Libwally](17_5_Using_Scripts_in_Libwally.md) 28 | * [Section Six: Using Other Functions in Libwally](17_6_Using_Other_Functions_in_Libwally.md) 29 | * [Section Seven: Integrating Libwally and Bitcoin-CLI](17_7_Integrating_Libwally_and_Bitcoin-CLI.md) 30 | -------------------------------------------------------------------------------- /18_0_Talking_to_Bitcoind_Other.md: -------------------------------------------------------------------------------- 1 | # Chapter 18: Talking to Bitcoind with Other Languages 2 | 3 | You should now have a solid foundation for working with Bitcoin in C, not only using RPC, JSON, and ZMQ libraries to directly interact with `bitcoind`, but also utilizing the Libwally libraries to complement that work. And C is a great language for prototyping and abstraction — but it's probably not what you're programming in. This chapter thus takes a whirlwind tour of six other programming languages, demonstrating the barest Bitcoin functionality in each and allowing you to expand the lessons of the command line and C to the programming language of your choice. 4 | 5 | Each of the sections contains approximately the same information, focused on: creating an RPC connection; examining the wallet; creating a new address, and creating a transaction. However, there's some variety among the languages, showing off different aspects of Bitcoin's RPC commands in different examples. In particular, some languages use the easy methodology of `sendtoaddress` while others use the hard methodology of creating a raw transaction from scratch. 6 | 7 | ## Objectives for This Chapter 8 | 9 | After working through this chapter, a developer will be able to: 10 | 11 | * Prepare Bitcoin Development Environments for a Variety of Languages 12 | * Use Wallet Functions in a Variety of Languages 13 | * Use Transaction Functions in a Variety of Languages 14 | 15 | Supporting objectives include the ability to: 16 | 17 | * Understand More about Bitcoin RPC through Interactions with a Variety of Languages 18 | 19 | ## Table of Contents 20 | 21 | * [Section One: Accessing Bitcoind with Go](18_1_Accessing_Bitcoind_with_Go.md) 22 | * [Section Two: Accessing Bitcoind with Java](18_2_Accessing_Bitcoind_with_Java.md) 23 | * [Section Three: Accessing Bitcoind with NodeJS](18_3_Accessing_Bitcoind_with_NodeJS.md) 24 | * [Section Four: Accessing Bitcoind with Python](18_4_Accessing_Bitcoind_with_Python.md) 25 | * [Section Five: Accessing Bitcoind with Rust](18_5_Accessing_Bitcoind_with_Rust.md) 26 | * [Section Six: Accessing Bitcoind with Swift](18_6_Accessing_Bitcoind_with_Swift.md) 27 | -------------------------------------------------------------------------------- /19_0_Understanding_Your_Lightning_Setup.md: -------------------------------------------------------------------------------- 1 | # Chapter 19: Understanding Your Lighting Setup 2 | 3 | > :information_source: **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning. 4 | 5 | The previous chapter concluded our work with Bitcoin proper, through CLI, scripting, and programming languages. However, there are many other utilities within the Bitcoin ecosystem: this chapter and the next cover what may be the biggest and most important: the Lightning Network. Here you'll begin work with the `lightning-cli` command-line interface, understanding a c-lightning setup and its features, including some examples and basic configuration. 6 | 7 | ## Objectives for This Chapter 8 | 9 | After working through this chapter, a developer will be able to: 10 | 11 | * Assess that a c-lightning Node is Installed and Up-to-date 12 | * Perform Basic Lightning Wallet Commands 13 | * Create a LIghtning Channel 14 | 15 | Supporting objectives include the ability to: 16 | 17 | * Understand the Basic Lightning Configuration 18 | * Understand the Interaction of Lightning Peers 19 | * Understand How to Lightning 20 | 21 | ## Table of Contents 22 | 23 | * [Section One: Verifying Your c-lightning Setup](19_1_Verifying_Your_Lightning_Setup.md) 24 | * [Section Two: Knowing Your c-lightning Setup](19_2_Knowing_Your_lightning_Setup.md) 25 | * [Interlude: Accessing a Second Lightning Node](19_2__Interlude_Accessing_a_Second_Lightning_Node.md) 26 | * [Section Three: Creating a Lightning Channel](19_3_Setting_Up_a_Channel.md) 27 | -------------------------------------------------------------------------------- /20_0_Using_Lightning.md: -------------------------------------------------------------------------------- 1 | # Chapter 20: Using Lightning 2 | 3 | > :information_source: **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning. 4 | 5 | In this chapter you'll continue work with the `lightning-cli` command-line interface. You'll create invoices, perform payments, and close channels — all of the major activities for using Lightning. 6 | 7 | ## Objectives for This Chapter 8 | 9 | After working through this chapter, a developer will be able to: 10 | 11 | * Perform payments on the Lightning Network. 12 | * Apply closure to a Lightning channel. 13 | 14 | Supporting objectives include the ability to: 15 | 16 | * Understand the format of invoices. 17 | * Understand the life cycle of Lightning Network payments. 18 | * Know how to expand the Lightning Network. 19 | 20 | ## Table of Contents 21 | 22 | * [Section One: Generating a Payment Request](20_1_Generate_a_Payment_Request.md) 23 | * [Section Two: Paying an Invoice](20_2_Paying_a_Invoice.md) 24 | * [Section Three: Closing a Lightning Channel](20_3_Closing_a_Channel.md) 25 | * [Section Four: Expanding the Lightning Network](20_4_Lightning_Network_Review.md) 26 | -------------------------------------------------------------------------------- /A0_Appendices.md: -------------------------------------------------------------------------------- 1 | # Appendices 2 | 3 | The main body of this course suggests a fairly standard setup for Bitcoin testing. What follows in these appendices are a better explanation of that setup and some options for alternatives. 4 | 5 | ## Objectives for This Section 6 | 7 | After working through these appendices, a developer will be able to: 8 | 9 | * Decide among Multiple Methods for Creating a Bitcoin Blockchain 10 | 11 | Supporting objectives include the ability to: 12 | 13 | * Understand the Bitcoin Standup Setup 14 | * Perform a Compilation of Bitcoin by Hand 15 | * Understand the Power of Regtest 16 | * Use a Regtest Environment 17 | 18 | ## Table of Contents 19 | 20 | * [Appendix One: Understanding Bitcoin Standup](A1_0_Understanding_Bitcoin_Standup.md) 21 | * [Appendix Two: Compiling Bitcoin from Source](A2_0_Compiling_Bitcoin_from_Source.md) 22 | * [Appendix Three: Using Bitcoin Regtest](A3_0_Using_Bitcoin_Regtest.md) 23 | -------------------------------------------------------------------------------- /A1_0_Understanding_Bitcoin_Standup.md: -------------------------------------------------------------------------------- 1 | # Appendix I: Understanding Bitcoin Standup 2 | 3 | [§2.1: Setting Up a Bitcoin Core VPS with StackScript](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md) explains the process of creating a Bitcoin node using [Bitcoin-Standup-Scripts](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts). The following appendix explains what the major sections of the script do. You may wish to follow along in [Linode Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts/blob/master/Scripts/LinodeStandUp.sh) in another window. 4 | 5 | ## Step 1: Hostname 6 | 7 | Your host's name is stored in `/etc/hostname` and set with the `hostname` command. It also appears in `/etc/hosts`. 8 | 9 | ## Step 2: Timezone 10 | 11 | Your host's timezone is stored in `/etc/timezone`, then an appropriate file from `/usr/share/zoneinfo/` is copied to `/etc/localtime` 12 | 13 | ## Step 3: Updating Debian 14 | 15 | The `apt-get` package manager is used to bring your machine up to date and to install `gnupg`, the random-number generator `haveged`, and the uncomplicated firewall `ufw`. 16 | 17 | Your machine is setup to automatically stay up to date with `echo "unattended-upgrades unattended-upgrades/enable_auto_updates boolean true" | debconf-set-selections`. 18 | 19 | ## Step 4: Setting Up a User 20 | 21 | A `standup` user is created, which will be used for your Bitcoin applications. It also has `sudo` permissions, allowing you to take privileged actions with this account. 22 | 23 | If you supplied an SSH key, it will allow you access to this account (otherwise, you must use the password you created in setup). 24 | 25 | If you supplied an IP address, `ssh` access will be limited to that address, per `/etc/hosts.allow`. 26 | 27 | ## Step 5: Setting Up Tor 28 | 29 | Tor is installed to provide protected (hidden) services to access Bitcoin's RPC commands through your server. See [§14.1: Verifying Your Tor Setup](14_1_Verifying_Your_Tor_Setup.md) for more information on your Tor Setup. 30 | 31 | If you supplied an authorized client for the hidden services, access will be limited to that key, per `/var/lib/tor/standup/authorized_clients`. If you did not, [§14.2](14_2_Changing_Your_Bitcoin_Hidden_Services.md) explains how to do so at a later date. 32 | 33 | ## Step 6: Installing Bitcoin 34 | 35 | Bitcoin is installed in `~standup/.bitcoin`. Your configuration is stored in `~standup/.bitcoin/bitcoin.conf`. 36 | 37 | Be sure that the checksums verified per [§2.1](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md), otherwise you could be exposed to a supply-chain attack. 38 | 39 | ## Step 7: Installing QR Encoder 40 | 41 | To keep everything compatible with [GordianSystem](https://github.com/BlockchainCommons/GordianSystem) a QR code is created at `/qrcode.png`. This can be read from a QuickConnect client such as [GordianWallet](https://github.com/BlockchainCommons/GordianWallet-iOS). 42 | 43 | ## Conclusion — Understanding Bitcoin Standup 44 | 45 | Bitcoin Standup uses scripts to try and match much of the functionality of a [GordianNode](https://github.com/BlockchainCommons/GordianNode-macOS). It should provide you with a secure Bitcoin environment built on a foundation of Bitcoin Core and Tor for RPC communications. 46 | 47 | ## What's Next? 48 | 49 | If you were in the process of creating a Bitcoin node for use in this course, you should return to [§2.1](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md). 50 | 51 | If you are reading through the appendices, continue with [Appendix II: Compiling Bitcoin from Source](A2_0_Compiling_Bitcoin_from_Source.md). 52 | -------------------------------------------------------------------------------- /CLA-signed/CLA.joa-rodrigues.90487FE3801DE403173A2EDBC685E6D937FDC203.asc: -------------------------------------------------------------------------------- 1 | -----BEGIN PGP SIGNED MESSAGE----- 2 | Hash: SHA512 3 | 4 | # Contributor License Agreement 5 | 6 | Version 1.0 7 | 8 | Name: `$name` 9 | 10 | E-Mail: `$email` 11 | 12 | Legal Jurisdiction: Wyoming, United States of America 13 | 14 | Project: https://github.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line 15 | 16 | Date: `$date` 17 | 18 | ## Purpose 19 | 20 | This agreement gives Blockchain Commons, LLC the permission it needs in order to accept my contributions into its open software project and to manage the intellectual property in that project over time. 21 | 22 | ## License 23 | 24 | I hereby license Blockchain Commons, LLC to: 25 | 26 | 1. do anything with my contributions that would otherwise infringe my copyright in them 27 | 28 | 2. do anything with my contributions that would otherwise infringe patents that I can or become able to license 29 | 30 | 3. sublicense these rights to others on any terms they like 31 | 32 | ## Reliability 33 | 34 | I understand that Blockchain Commons will rely on this license. I may not revoke this license. 35 | 36 | ## Awareness 37 | 38 | I promise that I am familiar with legal rules, like ["work made for hire" rules](http://worksmadeforhire.com), that can give employers and clients ownership of intellectual property in work that I do. I am also aware that legal agreements I might sign, like confidential information and invention assignment agreements, will usually give ownership of intellectual property in my work to employers, clients, and companies that I found. If someone else owns intellectual property in my work, I need their permission to license it. 39 | 40 | ## Copyright Guarantee 41 | 42 | I promise not to offer contributions to the project that contain copyrighted work that I do not have legally binding permission to contribute under these terms. When I offer a contribution with permission, I promise to document in the contribution who owns copyright in what work, and how they gave permission to contribute it. If I later become aware that one of my contributions may have copyrighted work of others that I did not have permission to contribute, I will notify Blockchain Commons, in confidence, immediately. 43 | 44 | ## Patent Guarantee 45 | 46 | I promise not to offer contributions to the project that I know infringe patents of others that I do not have permission to contribute under these terms. 47 | 48 | ## Open Source Guarantee 49 | 50 | I promise not to offer contributions that contain or depend on the work of others, unless that work is available under a license that [Blue Oak Council rates bronze or better](https://blueoakconcil.org/list), such as the MIT License, two- or three-clause BSD License, the Apache License Version 2.0, or the Blue Oak Model License 1.0.0. When I offer a contribution containing or depending on others' work, I promise to document in the contribution who licenses that work, along with copies of their license terms. 51 | 52 | ## Disclaimers 53 | 54 | ***As far as the law allows, my contributions come as is, without any warranty or condition. Other than under [Copyright Guarantee](#copyright-guarantee), [Patent Guarantee](#patent-guarantee), or [Open Source Guarantee](#open-source-guarantee), I will not be liable to anyone for any damages related to my contributions or this contributor license agreement, under any kind of legal claim.*** 55 | 56 | - --- 57 | 58 | To sign this Contributor License Agreement, fill in `$name`, `$email`, and `$date` above. Then sign using GPG using the following command `gpg --armor --clearsign --output ./CLA-signed/CLA.YOURGITHUBNAME.YOURGPGFINGERPRINT.asc CLA.md`, then either submit your signed Contributor License Agreement to this repo as a GPG signed Pull Request or email it to [ChristopherA@BlockchainCommons.com](mailto:ChristopherA@BlockchainCommons.com). 59 | -----BEGIN PGP SIGNATURE----- 60 | 61 | iHUEARYKAB0WIQSQSH/jgB3kAxc6LtvGhebZN/3CAwUCYfxLmQAKCRDGhebZN/3C 62 | AxImAQCBq6rX67QtcvLaUbZWGiGcb6Lwfh5Nfot2W1U0aX9MDgEAilSaykUsHmmb 63 | +dH7vvIb5o3Su5xstebNxx9wqbBL4Ao= 64 | =N//+ 65 | -----END PGP SIGNATURE----- 66 | -------------------------------------------------------------------------------- /CLA.md: -------------------------------------------------------------------------------- 1 | # Contributor License Agreement 2 | 3 | Version 1.0 4 | 5 | Name: `$name` 6 | 7 | E-Mail: `$email` 8 | 9 | Legal Jurisdiction: Wyoming, United States of America 10 | 11 | Project: https://github.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line 12 | 13 | Date: `$date` 14 | 15 | ## Purpose 16 | 17 | This agreement gives Blockchain Commons, LLC the permission it needs in order to accept my contributions into its open software project and to manage the intellectual property in that project over time. 18 | 19 | ## License 20 | 21 | I hereby license Blockchain Commons, LLC to: 22 | 23 | 1. do anything with my contributions that would otherwise infringe my copyright in them 24 | 25 | 2. do anything with my contributions that would otherwise infringe patents that I can or become able to license 26 | 27 | 3. sublicense these rights to others on any terms they like 28 | 29 | ## Reliability 30 | 31 | I understand that Blockchain Commons will rely on this license. I may not revoke this license. 32 | 33 | ## Awareness 34 | 35 | I promise that I am familiar with legal rules, like ["work made for hire" rules](http://worksmadeforhire.com), that can give employers and clients ownership of intellectual property in work that I do. I am also aware that legal agreements I might sign, like confidential information and invention assignment agreements, will usually give ownership of intellectual property in my work to employers, clients, and companies that I found. If someone else owns intellectual property in my work, I need their permission to license it. 36 | 37 | ## Copyright Guarantee 38 | 39 | I promise not to offer contributions to the project that contain copyrighted work that I do not have legally binding permission to contribute under these terms. When I offer a contribution with permission, I promise to document in the contribution who owns copyright in what work, and how they gave permission to contribute it. If I later become aware that one of my contributions may have copyrighted work of others that I did not have permission to contribute, I will notify Blockchain Commons, in confidence, immediately. 40 | 41 | ## Patent Guarantee 42 | 43 | I promise not to offer contributions to the project that I know infringe patents of others that I do not have permission to contribute under these terms. 44 | 45 | ## Open Source Guarantee 46 | 47 | I promise not to offer contributions that contain or depend on the work of others, unless that work is available under a license that [Blue Oak Council rates bronze or better](https://blueoakconcil.org/list), such as the MIT License, two- or three-clause BSD License, the Apache License Version 2.0, or the Blue Oak Model License 1.0.0. When I offer a contribution containing or depending on others' work, I promise to document in the contribution who licenses that work, along with copies of their license terms. 48 | 49 | ## Disclaimers 50 | 51 | ***As far as the law allows, my contributions come as is, without any warranty or condition. Other than under [Copyright Guarantee](#copyright-guarantee), [Patent Guarantee](#patent-guarantee), or [Open Source Guarantee](#open-source-guarantee), I will not be liable to anyone for any damages related to my contributions or this contributor license agreement, under any kind of legal claim.*** 52 | 53 | --- 54 | 55 | To sign this Contributor License Agreement, fill in `$name`, `$email`, and `$date` above. Then sign using GPG using the following command `gpg --armor --clearsign --output ./CLA-signed/CLA.YOURGITHUBNAME.YOURGPGFINGERPRINT.asc CLA.md`, then either submit your signed Contributor License Agreement to this repo as a GPG signed Pull Request or email it to [ChristopherA@BlockchainCommons.com](mailto:ChristopherA@BlockchainCommons.com). 56 | -------------------------------------------------------------------------------- /es/02_0_Configurando_un_Bitcoin-Core_VPS.md: -------------------------------------------------------------------------------- 1 | 2 | # Capítulo dos: Creando un Servidor Privado Virtual de Bitcoin-Core 3 | 4 | Para iniciar con Bitcoin, se debe configurar una maquina ejecutando el software de Bitcoin. Los artículos en este capítulo describen como hacerlo, principalmente mediante el uso de un VPS (servidor privado virtual). 5 | 6 | 7 | ## Objetivos de este capítulo 8 | 9 | Después de trabajar en este capítulo, un desarrollador podrá: 10 | 11 | * Decidir entre los cinco tipos principales de nodos de Bitcoin 12 | * Cree un nodo de Bitcoin para desarrollo. 13 | * Cree una instancia local de la Blockchain de Bitcoin 14 | 15 | Los objetivos de apoyo incluyen la capacidad de: 16 | 17 | * Comprender la configuración de red básica del VPS. 18 | * Decidir qué prioridades de seguridad implementar. 19 | * Comprender la diferencia entre nodos podados y no podados. 20 | * Comprender la diferencia entre los nodos Mainnet, Testnet y Regtest. 21 | * Interpretar los conceptos básicos del archivo de configuración de Bitcoin. 22 | 23 | ## Tabla de contenido 24 | 25 | En realidad, no es necesario leer este capítulo completo. Decida si desea ejecutar un StackScript para configurar un nodo en un VPS Linode (§2.2); o desea configurarlo en un entorno diferente, como en una máquina AWS o Mac (§2.3). Luego puede ir a la sección correspondiente. Información adicional sobre nuestras configuraciones sugeridas también se puede encontrar en el Apéndice I. 26 | 27 | * [Sección uno: Configurando un VPS Bitcoin-Core con Bitcoin Standup](02_1_Configurando_un_Bitcoin-Core_VPS_con_StackScript.md) 28 | * [Sección dos: Configurando una máquina Bitcoin-Core por otros medios](02_2_Configurando_Bitcoin_Core_Otros.md) 29 | -------------------------------------------------------------------------------- /es/02_2_Configurando_Bitcoin_Core_Otros.md: -------------------------------------------------------------------------------- 1 | # 2.2: Configuración de una máquina Bitcoin-Core a través de otros medios 2 | 3 | La sección anterior, [§2.1: Configuración de un VPS Bitcoin-Core con Bitcoin Standup](02_1_Configurando_un_Bitcoin-Core_VPS_con_StackScript.md), presumía que 4 | estaría creando un nodo completo en un VPS usando un Linode Stackscript. Sin embargo, puede crear una instancia de Bitcoin-Core a través de cualquier metodología de 5 | su elección y seguir los pasos posteriores de este tutorial. 6 | 7 | A continuación, se muestran otras metodologías de configuración que conocemos: 8 | 9 | * *[Compilación desde la fuente](A2_0_Compilando_Bitcoin_desde_la_Fuente.md).* Si prefiere compilar Bitcoin Core a mano, eso se trata en el Apéndice 2. 10 | * *[Usando GordianNode-macOS](https://github.com/BlockchainCommons/GordianNode-macOS).* Si tiene una Mac moderna, puede usar la aplicación *GordianNode* de 11 | Blockchain Commons, con tecnología *BitcoinStandup*, para instalar un nodo completo en su Mac. 12 | * *[Uso de otros scripts de Bitcoin Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts).* Blockchain Commons también ofrece una versión del 13 | script de Linode que se uso anteriormente y que se puede ejecutar desde la línea de comandos en cualquier máquina Debian o Ubuntu. Este tiende a ser un script 14 | de vanguardia, lo que significa que es más probable que presente nuevas funciones, como la instalación de Lightning. 15 | * *[Configuración de un nodo Bitcoin en AWS](https://wolfmcnally.com/115/developer-notes-setting-up-a-bitcoin-node-on-aws/).* @wolfmcnally ha escrito un tutorial 16 | paso a paso para configurar Bitcoin-Core con Amazon Web Services (AWS). 17 | * *[Configuración de un nodo Bitcoin en una Raspberry Pi 3](https://medium.com/@meeDamian/bitcoin-full-node-on-rbp3-revised-88bb7c8ef1d1).* Damian Mee explica 18 | cómo configurar una Nodo completo de forma sencilla en una Raspberry Pi 3. 19 | 20 | ## ¿Que sigue? 21 | 22 | A menos que desee volver a una de las otras metodologías para crear un nodo Bitcoin-Core, debe: 23 | 24 | * Continúe con "bitcoin-cli" con el [Capítulo tres: Entendiendo su configuración de Bitcoin](03_0_Entendiendo_Su_Configuracion_Bitcoin.md). 25 | -------------------------------------------------------------------------------- /es/03_0_Entendiendo_Su_Configuracion_Bitcoin.md: -------------------------------------------------------------------------------- 1 | # Capítulo Tres: Entendiendo Su Configuración Bitcoin 2 | 3 | Ahora está listo para comenzar a trabajar con la interfaz de línea de comandos `bitcoin-cli`. Pero eso primero requiere que comprenda la configuración de Bitcoin y las características de su billetera, que es lo que se explicará en este capítulo. 4 | 5 | Para este y futuros capítulos, suponemos que tiene un VPS con Bitcoin instalado, ejecutando `bitcoind`. También suponemos que está conectado a testnet, lo que le permite acceder a bitcoins sin utilizar fondos reales. Puede hacerlo con Bitcoin Standup en Linode.com, según [§2.1: Configuración de un Servidor Privado Virtual de Bitcoin-Core con Bitcoin Standup](02_1_Configurando_un_Bitcoin-Core_VPS_con_StackScript.md), o por otros medios, según [§2.2: Configuración de una Maquina Bitcoin-Core por Otros Medios](02_2_Configurando_Bitcoin_Core_Otros.md). 6 | 7 | ## Objetivos de este capítulo 8 | 9 | Después de trabajar en este capítulo, un desarrollador podrá: 10 | 11 | * Demostrar que su nodo Bitcoin está instalado y actualizado 12 | * Crear una dirección para recibir fondos de Bitcoin 13 | * Usar comandos básicos de billetera 14 | * Crear una dirección a partir de un descriptor 15 | 16 | Los objetivos de apoyo incluyen la capacidad de: 17 | 18 | * Comprender el diseño básico de archivos de Bitcoin 19 | * Usar comandos informativos básicos 20 | * Comprenda qué es una dirección de Bitcoin 21 | * Comprender qué es una billetera 22 | * Comprender cómo importar direcciones 23 | 24 | ## Tabla de contenido 25 | 26 | * [Sección Uno: Verificando Su Configuración Bitcoin](03_1_Verificando_Su_Configuracion_Bitcoin.md) 27 | * [Sección Dos: Conociendo Su Configuración Bitcoin](03_2_Conociendo_Su_Configuracion_Bitcoin.md) 28 | * [Sección Tres: Configurando Su Billetera](03_3_Configurando_Su_Billetera.md) 29 | * [Interludio: Usando Variables de la Linea de Comandos](03_3_Interludio_Usando_Variables_Linea_Comando.md) 30 | * [Sección Cuatro: Recibiendo una Transacción](03_4_Recibiendo_una_Transaccion.md) 31 | * [Sección Cinco: Entendiendo El Descriptor](03_5_Entendiendo_El_Descriptor.md) 32 | -------------------------------------------------------------------------------- /es/03_3_Interludio_Usando_Variables_Linea_Comando.md: -------------------------------------------------------------------------------- 1 | # Interludio: Usando variables de la línea de comandos 2 | 3 | La sección anterior demostró una serie de comandos de línea de comandos que se utilizan sin ofuscación ni interferencia. 4 | Sin embargo, a menudo esa no es la mejor manera de ejecutar Bitcoin desde la línea de comandos. 5 | Debido a que está tratando con variables largas, complejas e ilegibles, es fácil cometer un error si está copiando esas variables (o perder satoshis, si las está escribiendo a mano). 6 | Debido a que esas variables pueden significar la diferencia entre recibir y perder dinero real, no querrá cometer errores. 7 | Por estas razones, recomendamos encarecidamente utilizar variables de línea de comandos para guardar direcciones, firmas u otras cadenas largas de información siempre que sea razonable hacerlo. 8 | 9 | Si está utilizando `bash`, puede guardar la información en una variable como esta: 10 | ``` 11 | $ VARIABLE=$(command) 12 | ``` 13 | Esa es una simple sustitución de comando, el equivalente a ``VARIABLE=`command` ``. El comando entre paréntesis se ejecuta y luego se asigna a la VARIABLE. 14 | 15 | Para crear una nueva dirección se vería así: 16 | ``` 17 | $ unset NEW_ADDRESS_1 18 | $ NEW_ADDRESS_1=$(bitcoin-cli getnewaddress "" legacy) 19 | ``` 20 | 21 | Estos comandos borran la variable NEW_ADDRESS_1, solo para estar seguros, luego la llenan con los resultados del comando `bitcoin-cli getnewaddress`. 22 | 23 | Luego puede usar el comando `echo` de su shell para ver su dirección (nueva): 24 | ``` 25 | $ echo $NEW_ADDRESS_1 26 | mi25UrzHnvn3bpEfFCNqJhPWJn5b77a5NE 27 | ``` 28 | Debido a que tiene su dirección en una variable, ahora puede firmar fácilmente un mensaje para esa dirección, sin preocuparse por escribir mal la dirección. ¡Por supuesto, también guardará esa firma en una variable! 29 | 30 | ``` 31 | $ NEW_SIG_1=$(bitcoin-cli signmessage $NEW_ADDRESS_1 "Hello, World") 32 | $ echo $NEW_SIG_1 33 | IPYIzgj+Rg4bxDwCyoPiFiNNcxWHYxgVcklhmN8aB2XRRJqV731Xu9XkfZ6oxj+QGCRmTe80X81EpXtmGUpXOM4= 34 | ``` 35 | El resto de este tutorial utilizará este estilo de guardar información en variables cuando sea práctico. 36 | 37 | 38 | > :book: ***¿Cuándo no es práctico utilizar variables de línea de comandos?*** Las variables de la línea de comandos no son prácticas si necesita usar la información en otro lugar que no sea la línea de comandos. Por ejemplo, es posible que guardar su firma no sea realmente útil si solo va a tener que enviársela a otra persona en un correo electrónico. Además, algunos comandos futuros generarán objetos JSON en lugar de información simple, y las variables no se pueden usar para capturar esa información ... al menos no sin un poco más de trabajo 39 | 40 | ## Resumen: Usando variables de la línea de comandos 41 | 42 | Las variables de la línea de comandos se pueden usar para contener cadenas largas de Bitcoin, lo que minimiza las posibilidades de errores. 43 | 44 | ## ¿Que sigue? 45 | 46 | Continúe "Comprendiendo la configuración de Bitcoin" en [§3.4: Recibiendo una transacción](03_4_Recibiendo_una_Transaccion.md). 47 | -------------------------------------------------------------------------------- /es/04_0_Enviando_Transacciones_Bitcoin.md: -------------------------------------------------------------------------------- 1 | # Capítulo Cuatro: Enviando Transacciones en Bitcoin 2 | 3 | Este capítulo describe tres metodos diferentes para enviar bitcoins a direcciones tipicas P2PKH desde la línea de comandos, usando unicamente la interfaz de bitcoin-cli. 4 | 5 | ## Objetivos de este Capítulo 6 | 7 | Después de trabajar en este capítulo, un desarrollador podrá: 8 | 9 | * Decidir cómo enviar dinero a través de Bitcoin 10 | * Crear una transacción en crudo 11 | * Utilizar la aritmética para calcular las tarifas 12 | 13 | Con los objetivos complementarios se tendrá la habilidad de: 14 | 15 | * Entender las transacciones y sus comisiones 16 | * Entender las transacciones de tipo Legacy & SegWit 17 | * Usar métodos básicos para enviar dinero 18 | * Usar métodos automaticos para calcular comisiones para enviar dinero 19 | * Entender el peligro de las transacciones sin procesar 20 | 21 | ## Tabla de contenido 22 | 23 | * [Sección Uno: Enviando Monedas de la Forma Fácil](04_1_Enviando_Monedas_de_la_Forma_Facil.md) 24 | * [Sección Dos: Creando una Transacción Cruda](04_2_Creando_una_Transaccion_Cruda.md) 25 | * [Interludio: Usando JQ](04_2_Interludio_Usando_JQ.md) 26 | * [Sección Tres: Creando una Transacción Cruda con Argumentos Ingresados con Nombre](04_3_Creando_una_Transaccion_Cruda_con_Argumentos_Ingresados_con_Nombre.md) 27 | * [Sección Cuatro: Enviando Monedas con una Transacción Cruda](04_4_Enviando_Monedas_con_una_Transaccion_Cruda.md) 28 | * [Interludio: Usando Curl](04_4_Interludio_Usando_Curl.md) 29 | * [Sección Cinco: Enviando Monedas con Transacciones Crudas Automatizadas](04_5_Enviando_Monedas_con_Transacciones_Crudas_Automatizadas.md) 30 | * [Sección Seis: Creando una Transacción Segwit](04_6_Creando_una_Transaccion_Segwit.md) 31 | 32 | -------------------------------------------------------------------------------- /es/05_0_Controlando_Transacciones_Bitcoin.md: -------------------------------------------------------------------------------- 1 | # Capitulo Cinco: Controlar Las Transacciones de Bitcoin 2 | 3 | Enviar una transacción no siempre es el final de la historia. Al usar los protocolos RBF (reemplazo por tarifa) y CPFP (el niño paga por el padre), un desarrollador puede continuar controlando la transacción después de que se haya enviado, para mejorar la eficiencia o recuperar transacciones que se atascan. Estos métodos comenzarán a destacar el verdadero poder de Bitcoin. 4 | 5 | ## Objetivos de Esta Sección: 6 | 7 | Después de trabajar en este capítulo, un desarrollador podrá: 8 | 9 | * Decida si RBF o CPFP pueden ayudar en una transacción 10 | * Crear transacción de reemplazo usando RBF 11 | * Crear nuevas transacciones con CPFP 12 | 13 | Los objetivos de apoyo incluyen la capacidad de: 14 | 15 | * Entender la mempool 16 | * Comprenda la diferencia entre RBF y CPFP 17 | * Planifique el poder de RBF 18 | 19 | ## Tabla de Contenido 20 | 21 | * [Sección uno: Vigilando por Transacciones Estancadas](05_1_Vigilando_por_Transacciones_Estancadas.md) 22 | * [Sección dos: Reenviando una Transacción con RBF](05_2_Reenviando_a_Transaccion_con_RBF.md) 23 | * [Sección tres: Financiando una Transacción con CPFP](05_3_Financiando_una_Transaccion_con_CPFP.md) 24 | -------------------------------------------------------------------------------- /es/06_0_Expandiendo_las_Transacciones_Bitcoin_con_Multifirmas.md: -------------------------------------------------------------------------------- 1 | # Capítulo Seis: Expandiendo Transacciones Bitcoin con Multifirmas 2 | 3 | Transacciones básicas Bitcoin: (1) enviar fondos; (2) a un destinatario P2PKH simple o SegWit; (3) desde una máquina; (4) inmediatamente. Sin embargo, estas cuatro partes de esta definición pueden expandirse usando transacciones Bitcoin más complejas. Este primer capítulo de "Expansión" muestra cómo variar puntos (2) y (3) enviando dinero a una dirección que representa a múltiples destinatarios (o al menos, múltiples firmantes). 4 | 5 | ## Objectivos para Esta Sección 6 | 7 | Luego de trabajar a lo largo de este capítulo, un desarrollador será capaz de: 8 | 9 | * Crear Direcciones Bitcoin Multifirma Usando los Fundamentos de Bitcoin 10 | * Crear Direcciones Bitcoin Multifirma Usando Mecanismos más Sencillos 11 | 12 | Los objetivos propuestos incluyen la habilidad de: 13 | 14 | * Comprender Cómo Gastar Fondos Enviados a una Multifirma 15 | * Planificar el Poder de las Multifirmas 16 | 17 | ## Tabla de Contenidos 18 | 19 | * [Sección Uno: Enviando una Transacción a una Dirección Multifirma](06_1_Enviando_una_Transaccion_a_una_Direccion_Multifirma.md) 20 | * [Sección Dos: Gastando una Transacción con una Dirección Multifirma](06_2_Gastando_una_Transaccion_con_una_Direccion_Multifirma.md) 21 | * [Sección Tres: Enviando y Gastando una Multifirma Automatizada](06_3_Enviando_una_Multifirma_Automatizada.md) 22 | -------------------------------------------------------------------------------- /es/07_0_Expandiendo_las_Transacciones_Bitcoin_con_PSBTs.md: -------------------------------------------------------------------------------- 1 | # Expandiendo las Transacciones Bitcoin con PSBTs 2 | 3 | En el capítulo anterior se discutió cómo usar las múltiples fnuciones para determinar de manera colaborativa el consentimiento entre múltiples partes. No es la única forma de colaborar en la creación de transacciones de Bitcoin. Los PSBT son una tecnología mucho más nueva que le permite colaborar en una variedad de etapas, incluida la creación, financión y autenticación de una transacción de Bitcoin. 4 | 5 | ## Objetivos de esta sección 6 | 7 | Después de trabajar en este capítulo, un desarrollador podrá: 8 | 9 | * Crear transacciones con PSBT 10 | * Utilizar herramientas de línea de comandos para completar PSBT 11 | * Usar HWI para interactuar con una billetera de hardware 12 | 13 | Los objetivos de apoyo incluyen la capacidad de: 14 | 15 | * Comprender en qué se diferencian los PSBT de las multifirmas 16 | * Comprender el flujo de trabajo completo de trabajar con PSBT 17 | * Planear para el poder de las PSBT 18 | * Comprender el uso de una billetera de hardware 19 | 20 | ## Tabla de contenidos 21 | 22 | * [Sección Uno: Creando una Transacción Bitcoin Parcialmente Firmada](07_1_Creando_una_Transaccion_Bitcoin_Parcialmente_Firmada.md) 23 | * [Sección Dos: Usando una Transacción Bitcoin Parcialmente Firmada](07_2_Usando_una_Transaccion_Bitcoin_Parcialmente_Firmada.md) 24 | * [Sección Tres: Integrando con Hardware Wallets](07_3_Integrando_con_Hardware_Wallets.md) 25 | 26 | -------------------------------------------------------------------------------- /es/08_0_Expandiendo_Bitcoin_Transacciones_Otros.md: -------------------------------------------------------------------------------- 1 | # Capítulo ocho: Expandiendo las transacciones de Bitcoin de otras formas 2 | 3 | En la definición de transacciones básicas en el [Capítulo Seis](06_0_Expandiendo_las_Transacciones_Bitcoin_con_Multifirmas.md) se comentó que se enviaron _fondos_ _inmediatamente_, sin embargo ambos son elementos que se pueden cambiar. Esta sección final sobre la expansión de las transacciones de Bitcoin habla sobre cómo enviar cosas que no sean dinero en efectivo y cómo hacerlo en otro momento que no sea ahora. 4 | 5 | ## Objetivos de esta sección 6 | 7 | Después de trabajar en este capítulo, un desarrollador podrá: 8 | 9 | * Crear transacciones con tiempos de bloqueo 10 | * Crear transacciones con datos 11 | 12 | Los objetivos de apoyo incluyen la capacidad de: 13 | 14 | * Comprender los diferentes tipos de bloqueos de tiempo 15 | * Planificar para el poder del bloqueo de tiempo 16 | * Planificar para el poder de OP_RETURN 17 | 18 | ## Tabla de contenido 19 | 20 | * [Sección uno: Enviando una transacción con bloqueo de tiempo](08_1_Enviando_una_Transaccion_con_Bloqueo_de_Tiempo.md) 21 | * [Sección dos: Enviando una transacción con datos](08_2_Enviando_una_Transaccion_con_Datos.md) 22 | -------------------------------------------------------------------------------- /es/09_0_Introduciendo_Bitcoin_Scripts.md: -------------------------------------------------------------------------------- 1 | # Capítulo 9: Introduciendo Bitcoin Scripts 2 | 3 | Hasta la fecha, hemos estado interactuando con Bitcoin a un nivel de abstracción relativamente alto. El programa `bitcoin-cli` ofrece acceso a una variedad de comandos RPC que admiten la creación y el control de transacciones de Bitcoin sin procesar que incluyen fondos, datos, bloqueos de tiempo y multisigs. 4 | 5 | Sin embargo, Bitcoin ofrece mucha más complejidad que eso. Incluye un lenguaje de programación simple que se puede utilizar para crear condiciones de canje aún más complejas. Si las multifirma y los bloqueos de tiempo proporcionaron las bases de los contratos inteligentes, entonces Bitcoin Script se cimienta en esa base. Es el siguiente paso para empoderar a Bitcoin. 6 | 7 | ## Objetivos de este capítulo 8 | 9 | Después de trabajar en este capítulo, un desarrollador podrá: 10 | 11 | * Diseñar un script de Bitcoin 12 | * Aplicar un script de Bitcoin 13 | 14 | Los objetivos de apoyo incluyen la capacidad de: 15 | 16 | * Comprender el propósito de los scripts de Bitcoin 17 | * Comprender el script P2PKH 18 | * Comprender cómo funciona P2WPKH con secuencias de comandos 19 | * Comprender las necesidades de las pruebas de scripts de Bitcoin 20 | 21 | ## Tabla de contenido 22 | 23 | * [Sección uno: Entendiendo la base de las transacciones](09_1_Entendiendo_la_Base_de_las_Transacciones.md) 24 | * [Sección dos: Ejecución de un script de Bitcoin](09_2_Ejecutando_un_Script_Bitcoin.md) 25 | * [Sección tres: Probando un Script Bitcoin](09_3_Probando_un_Script_Bitcoin.md) 26 | * [Sección cuatro: Codificando una P2PKH](09_4_Codificando_una_P2PKH.md) 27 | * [Sección cinco: Codificando una P2WPKH](09_5_Codificando_una_P2WPKH.md) 28 | -------------------------------------------------------------------------------- /es/10_0_Embebiendo_Bitcoin_Scripts_en_Transacciones_P2SH.md: -------------------------------------------------------------------------------- 1 | # Capítulo 10: Incrustación de Bitcoin Scripts en Transacciones P2SH 2 | 3 | Bitcoin Script desciende varios niveles de abstracción, lo que le permite controlar minusciosamente las condiciones de canje de los fondos de Bitcoin. Pero, ¿cómo incorpora realmente esos Bitcoin Scripts en las transacciones que ha estado construyendo hasta la fecha? La respuesta es un nuevo tipo de transacción de Bitcoin, el P2SH. 4 | 5 | ## Objetivos de Este Capítulo 6 | 7 | Después de trabajar en este capítulo, un desarrollador podrá: 8 | 9 | * Diseñar una Transacción P2SH 10 | * Aplicar un Bitcoin Script P2SH 11 | 12 | Los objetivos de apoyo incluyen la capacidad de: 13 | 14 | * Comprender el Script P2SH 15 | * Comprender el Script Multifirma 16 | * Comprender las Diversas Variaciones de los Scripts de Segwit 17 | * Comprender Cómo Gastar Fondos Enviados a un P2SH 18 | 19 | ## Tabla de Contenido 20 | 21 | * [Sección Uno: Comprender la Base de P2SH](10_1_Entendiendo_la_Base_de_P2SH.md) 22 | * [Sección Dos: Construyendo la Estructura de P2SH](10_2_Construyendo_la_Estructura_de_P2SH.md) 23 | * [Sección Tres: Ejecución de un Bitcoin Script con P2SH](10_3_Ejecutando_un_Script_Bitcoin_con_P2SH.md) 24 | * [Sección Cuatro: Creación de un Script de Multifirma](10_4_Codificando_una_Multifirma.md) 25 | * [Sección Cinco: Creación de un Script de Segwit](10_5_Codificando_un_Script_Segwit.md) 26 | * [Sección Seis: Gasto en Transacciones P2SH](10_6_Gastando_una_Transaccion_P2SH.md) 27 | -------------------------------------------------------------------------------- /es/10_3_Ejecutando_un_Script_Bitcoin_con_P2SH.md: -------------------------------------------------------------------------------- 1 | # 10.3: Ejecución de un Bitcoin Script con P2SH 2 | 3 | Ahora que concoce la teoría y la práctica detrás de las direcciones P2SH, está listo para convertir un script de Bitcoin no estándar en una transacción real. Reutilizaremos la secuencia de comandos de bloqueo simple de [§9.2: Ejecución de un Bitcoin Script](09_2_Ejecutando_un_Script_Bitcoin.md), `OP_ADD 99 OP_EQUAL`. 4 | 5 | ## Crear una Transacción P2SH 6 | 7 | Para bloquear una transacción con este script, haga lo siguiente: 8 | 9 | 1. Serializar `OP_ADD 99 OP_EQUAL`: 10 | 1. OP_ADD = 0x93 — una traducción simple de un opcode 11 | 2. 99 = 0x01, 0x63 — este opcode empuja un byte a la pila, 99 (hex: 0x63) 12 | * No se preocupe por la conversión endian porque es solo un byte 13 | 3. OP_EQUAL = 0x87 — una tradducion simple de un opcode 14 | 4. `` = "93016387" 15 | 16 | ``` 17 | $ btcc OP_ADD 99 OP_EQUAL 18 | 93016387 19 | ``` 20 | 21 | 2. Guarde `` para referencia futura como `redeemScript`. 22 | 1. `` = "93016387" 23 | 3. SHA-256 y RIPEMD-160 hash el script serializado. 24 | 1. `` = "3f58b4f7b14847a9083694b9b3b52a4cea2569ed" 25 | 4. Produzca un script de bloqueo P2SH que incluya el ``. 26 | 1. `scriptPubKey` = "a9143f58b4f7b14847a9083694b9b3b52a4cea2569ed87" 27 | 28 | Luego puede crear una transacción usando esta `scriptPubKey`, probablemente a través de una API. 29 | 30 | ## Desbloquear la Transacción P2SH 31 | 32 | Para desbloquear esta transacción se requiere que el destinatario produzca un `scriptSig` que anteponga dos constantes que sumen noventa y nueve al script serializado: `1 98 `. 33 | 34 | ### Ejecute la Primera Ronda de Validación 35 | 36 | El proceso de desbloqueo de la transacción P2SH comienza con una primera ronda de validación, que verifica que el script de canje coincida con el valor hash en el script de bloqueo. 37 | 38 | Concatenar `scriptSig` y `scriptPubKey` y ejecutarlos, como de costumbre: 39 | ``` 40 | Script: 1 98 OP_HASH160 OP_EQUAL 41 | Stack: [] 42 | 43 | Script: 98 OP_HASH160 OP_EQUAL 44 | Stack: [ 1 ] 45 | 46 | Script: OP_HASH160 OP_EQUAL 47 | Stack: [ 1 98 ] 48 | 49 | Script: OP_HASH160 OP_EQUAL 50 | Stack: [ 1 98 ] 51 | 52 | Script: OP_EQUAL 53 | Running: OP_HASH160 54 | Stack: [ 1 98 ] 55 | 56 | Script: OP_EQUAL 57 | Stack: [ 1 98 ] 58 | 59 | Script: 60 | Running: OP_EQUAL 61 | Stack: [ 1 98 True ] 62 | ``` 63 | La secuencia de comandos termina con un `True` en la parte superior de la pila, por lo que tiene éxito ... a pesar de que hay otros cruft debajo de él. 64 | 65 | Sin embargo, debido a que se trataba de un script P2SH, la ejecución no se realiza. 66 | 67 | ### Ejecute la Segunda Ronda de Validación 68 | 69 | Para la segunda ronda de validación, verifique que los valores en el script de desbloqueo satisfagan el `redeemScript`: deserialice el `redeemScript` ("93016387" = "OP_ADD 99 OP_EQUAL"), luego ejecútelo usando los elementos del `scriptSig` antes del script serializado: 70 | 71 | ``` 72 | Script: 1 98 OP_ADD 99 OP_EQUAL 73 | Stack: [ ] 74 | 75 | Script: 98 OP_ADD 99 OP_EQUAL 76 | Stack: [ 1 ] 77 | 78 | Script: OP_ADD 99 OP_EQUAL 79 | Stack: [ 1 98 ] 80 | 81 | Script: 99 OP_EQUAL 82 | Running: 1 98 OP_ADD 83 | Stack: [ 99 ] 84 | 85 | Script: OP_EQUAL 86 | Stack: [ 99 99 ] 87 | 88 | Script: 89 | Running: 99 99 OP_EQUAL 90 | Stack: [ True ] 91 | ``` 92 | Con esa segunda validación _también_ verdadera, el UTXO ahora se puede gastar! 93 | 94 | ## Resumen: Creación de un Bitcoin Script con P2SH 95 | 96 | Una vez que conozca la técnica de construcción de P2SH, cualquier script se puede incrustar en una transacción de Bitcoin; y una vez que comprenda la técnica de validación de P2SH, es fácil ejecutar los scripts en dos rondas. 97 | 98 | ## Que Sigue? 99 | 100 | Continúe "Incrustando Bitcoin Scripts" con [§10.4: Codificando una Multifirma](10_4_Codificando_una_Multifirma.md). 101 | -------------------------------------------------------------------------------- /es/10_6_Gastando_una_Transaccion_P2SH.md: -------------------------------------------------------------------------------- 1 | # 10.6: Gastando una Transacción P2SH 2 | 3 | Antes de cerrar esta descripcion general de las transacciones P2SH, veremos cómo gastarlas. Esta sección es principalmente una descripción general, que hace referencia a una sección anterior en la que _ya_ gastamos una transacción P2SH. 4 | 5 | ## Utilice el Guión de Canjear 6 | 7 | Como vimos en [§6.2: Gastando una Transacción con una Multifirma](06_2_Gastando_una_Transaccion_con_una_Direccion_Multifirma.md), gastar una transacción P2SH se trata de tener esa versión serializada del script de bloqueo, el llamado _redeemScript_. Entonces, el primer paso para poder gastar una transacción P2SH es asegurarse de guardar el _redeemScript_ antes de dar la dirección P2SH a todos. 8 | 9 | ### Recoge Sus Variables 10 | 11 | Debido a que las direcciones P2SH distintas de las direcciones segwit anidadas y mulifirmas especiales no están integradas en `bitcoin-cli` no habrá atajos para el gasto P2SH como viste en [§6.3: Enviando una Multifirma Automatizada](06_3_Enviando_una_Multifirma_Automatizada.md). ¡Necesitará recopilar todas las variables más complejas por su cuenta! 12 | 13 | Esto significa que debe recopilar: 14 | 15 | * El `hex` de la `scriptPubKey` para la transacción que está gastando 16 | * El `redeemScript` serializado 17 | * Cualquier clave privada, ya que estará firmando a mano 18 | * Todos los `txids`, `vouts`, y `direcciones` regulares que necesitaría 19 | 20 | ## Crear la Transacción 21 | 22 | Como vimos en §6.2, la creación de una transacción es bastante estándar: 23 | ``` 24 | $ rawtxhex=$(bitcoin-cli -named createrawtransaction inputs='''[ { "txid": "'$utxo_txid'", "vout": '$utxo_vout' } ]''' outputs='''{ "'$recipient'": 0.00005}''') 25 | $ echo $rawtxhex 26 | 020000000121654fa95d5a268abf96427e3292baed6c9f6d16ed9e80511070f954883864b10000000000ffffffff0188130000000000001600142c48d3401f6abed74f52df3f795c644b4398844600000000 27 | ``` 28 | Sin embargo, la firma requiere ingresar información adicional para (1) `scriptPubKey`; (2) el `redeemScript`; y (3) cualquier clave privada requerida. 29 | 30 | Este es el ejemplo de cómo hacerlo para esa multifirma incrustada en P2SH en §6.2: 31 | ``` 32 | $ bitcoin-cli -named signrawtransactionwithkey hexstring=$rawtxhex prevtxs='''[ { "txid": "'$utxo_txid'", "vout": '$utxo_vout', "scriptPubKey": "'$utxo_spk'", "redeemScript": "'$redeem_script'" } ]''' privkeys='["cNPhhGjatADfhLD5gLfrR2JZKDE99Mn26NCbERsvnr24B3PcSbtR"]' 33 | ``` 34 | Con cualquier otro tipo de P2SH, incluirá un `redeemscript` diferente, pero por lo demás, la práctica es exactamente la misma. La única diferencia es que después de dos capítulos de trabajo en Scripts, ahora comprende qué es el `scriptPubKey` y qué es el `redeemScript`, así que con suerte lo que eran elementos misteriosos hace cuatro capítulos ahora es viejo sombrero. 35 | 36 | ## Resumen: Gastar una Transacción P2SH 37 | 38 | Ya gastó un P2SH en el Capítulo 6, cuando reenvió una transacción multifirma de la manera difícil, lo que requirió alinear la información de `scriptPubKey` y `redeemScript`. Ahora sabe que el `scriptPubKey` es un script de bloqueo P2SH estandarizado, mientras que el `redeemScript` coincide con un hash en ese script de bloqueo y que necesita poder ejecutarlo con las variables adecuadas para recibir un resultado `True`. Pero aparte de saber más, no hay nada nuevo en gastar una transacciónn P2SH, porque ya lo hizo! 39 | 40 | ## Que Sigue? 41 | 42 | Avanzar a través de "Bitcoin Scripting" con el [Capítulo Once: Potenciando Bloqueos de Tiempo con Bitcoin Scripts](11_0_Potenciando_Bloqueos_de_Tiempo_con_Bitcoin_Scripts.md). 43 | -------------------------------------------------------------------------------- /es/11_0_Potenciando_Bloqueos_de_Tiempo_con_Bitcoin_Scripts.md: -------------------------------------------------------------------------------- 1 | # Capitulo 11: Potenciando Bloqueos de Tiempo con Bitcoin Scripts 2 | 3 | La mejora que introdujo `nLockTime` en [§8.1](08_1_Enviando_una_Transaccion_con_Bloqueo_de_Tiempo.md) fue solo el comienzo del principio de los bloqueos de tiempo. Cuando comienza a escribir Bitcoin Scripts, dispone de dos opcodes de bloqueo de tiempo. 4 | 5 | ## Objetivos para este Capitulo 6 | 7 | Después de trabajar en este capítulo, un desarrollador podrá: 8 | 9 | * Decidir cual bloqueo de tiempo usar. 10 | * Crear Scripts con CLTV. 11 | * Crear Scripts con CSV. 12 | 13 | Los objetivos de apoyo incluyen la capacidad de: 14 | 15 | * Entender las diferencias entre los diferentes bloqueos de tiempo. 16 | * Generar tiempos relativos. 17 | 18 | ## Tabla de contenido: 19 | 20 | * [Sección Uno: Entendiendo las Opciones de los Bloqueos de Tiempo](11_1_Entendiendo_las_Opciones_de_los_Bloqueos_de_Tiempo.md) 21 | * [Sección Dos: Usando CLTV en Scripts](11_2_Usando_CLTV_en_Scripts.md) 22 | * [Sección Tres: Usando CSV en Scripts](11_3_Usando_CSV_en_Scripts.md) 23 | 24 | -------------------------------------------------------------------------------- /es/12_0_Expandiendo_Scripts_Bitcoin.md: -------------------------------------------------------------------------------- 1 | # Capítulo 12: Expandiendo los scripts de Bitcoin 2 | 3 | Todavía hay un poco más en los scripts de Bitcoin. Los condicionales le brindan acceso completo al control de flujo, mientras que una variedad de otros códigos de operación pueden ampliar sus posibilidades. 4 | 5 | ## Objetivos de este capítulo 6 | 7 | Después de trabajar en este capítulo, un desarrollador podrá: 8 | 9 | * Decidir cómo utilizar los scripts condicionales 10 | * Decidir cómo utilizar otros códigos de operación de script 11 | 12 | Los objetivos de apoyo incluyen la capacidad de: 13 | 14 | * Comprender la gama completa de posibilidades del Scripting 15 | * Identificar cómo obtener más información sobre los códigos de operación (opcodes) 16 | 17 | ## Tabla de contenido 18 | 19 | * [Sección uno: Usando scripts condicionales](12_1_Usando_Script_Condicionales.md) 20 | * [Sección dos: Usando otros comandos de scripting](12_2_Usando_Otros_Comandos_de_Scripting.md) 21 | -------------------------------------------------------------------------------- /es/13_0_Disenando_Bitcoin_Scripts_Reales.md: -------------------------------------------------------------------------------- 1 | # Capítulo 13: Diseñando Bitcoin Scripts Reales 2 | 3 | Nuestros scripts de Bitcoin hasta la fecha han sido en gran parte ejemplos teóricos, porque todavía hemos estado juntando las piezas del rompecabezas. Ahora, con el repertorio completo de Bitcoin Script en la mano, estamos listos para profundizar en varios Scripts de Bitcoin del mundo real y ver cómo funcionan. 4 | 5 | ## Objetivos de este capítulo 6 | 7 | Después de trabajar en este capítulo, un desarrollador podrá: 8 | 9 | * Evaluar los scripts de Bitcoin del mundo real 10 | * Crear scripts de Bitcoin del mundo real 11 | 12 | Los objetivos de apoyo incluyen la capacidad de: 13 | 14 | * Comprender los scripts de Bitcoin existentes 15 | * Comprender la importancia de las firmas 16 | 17 | ## Tabla de contenido 18 | 19 | * [Sección uno: Escribiendo scripts rompecabezas](13_1_Escribiendo_Puzzle_Scripts.md) 20 | * [Sección dos: Escribiendo scripts multifirma complejos](13_2_Escribiendo_Scripts_Multifirma_Complejos.md) 21 | * [Sección tres: Potenciando Bitcoin con Scripts](13_3_Potenciando_Bitcoin_con_Scripts.md) 22 | -------------------------------------------------------------------------------- /es/14_0_Usando_Tor.md: -------------------------------------------------------------------------------- 1 | # Capítulo 14: Usando Tor 2 | 3 | Tor es uno de los programas estándar instalados por [Bitcoin Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts). Ayudará a mantener su servidor seguro, lo cual es de vital importancia cuando se trata de criptomonedas. Este capítulo se aparta momentáneamente de Bitcoin para ayudarlo a comprender esta infraestructura de seguridad central. 4 | 5 | ## Objetivos de este capítulo 6 | 7 | Después de trabajar en este capítulo, un desarrollador podrá: 8 | 9 | * Usar una configuración de Tor 10 | * Realizar el mantenimiento de Tor 11 | 12 | Los objetivos de apoyo incluyen la capacidad de: 13 | 14 | * Comprender la red Tor 15 | * Comprender los distintos puertos de Bitcoin 16 | 17 | ## Table of Contents 18 | 19 | * [Sección uno: Verificación de la configuración de Tor](14_1_Verificando_Su_Configuracion_Tor.md) 20 | * [Sección dos: Cambiar sus servicios ocultos de Bitcoin](14_2_Cambiando_Sus_Servicios_Bitcoin_Ocultos.md) 21 | * [Sección tres: Agregar servicios ocultos SSH](14_3_Agregando_Servicios_SSH_Ocultos.md) 22 | -------------------------------------------------------------------------------- /es/14_2_Cambiando_Sus_Servicios_Bitcoin_Ocultos.md: -------------------------------------------------------------------------------- 1 | # Capítulo 14.2: Cambiar sus servicios ocultos de Bitcoin 2 | 3 | > :information_source: **NOTA:** Esta sección se ha agregado recientemente al curso y es un borrador inicial que aún puede estar pendiente de revisión. Lectura de advertencias. 4 | 5 | Tiene un servicio Tor en funcionamiento, pero con el tiempo es posible que desee restablecerlo o ajustarlo. 6 | 7 | ## Asegure sus servicios ocultos 8 | 9 | Tor le permite limitar qué clientes hablan con sus servicios ocultos. Si aún no autorizó a su cliente durante la configuración de su servidor debe hacer lo siguiente: 10 | 11 | 12 | 1. Solicite su clave pública de autenticación Tor V3 a su cliente. (En [GordianWallet](https://github.com/BlockchainCommons/GordianWallet-iOS), está disponible en el menú de configuración) 13 | 2. Vaya al subdirectorio apropiado para su servicio oculto de Bitcoin, que si utilizó Bitcoin Standup es `/var/lib/tor/standup/`. 14 | 3. Vaya al subdirectorio `authorized_clients`. 15 | 4. Agregue un archivo llamado `[anything].auth`. El `[anything]` puede ser cualquier cosa realmente. 16 | 5. Coloque la clave pública (y nada más) en el archivo. 17 | 18 | Una vez que haya agregado un archivo `.auth` al subdirectorio `authorized_client`, solo los clientes autorizados podrán comunicarse con ese servicio oculto. Puede agregar ~330 claves públicas diferentes para habilitar diferentes clientes. 19 | 20 | ## Restabelcer su dirección de cebolla para `bitcoind` 21 | 22 | Si alguna vez desea restablecer su dirección de cebolla para `bitcoind`, simplemente elimine la `onion_private_key` en su directorio de datos, como por ejemplo `~/.bitcoin/testnet`: 23 | ``` 24 | $ cd ~/.bitcoin/testnet 25 | $ rm onion_private_key 26 | ``` 27 | Cuando reinicie, se generará una nueva dirección de cebolla: 28 | ``` 29 | 2020-07-22T23:52:27Z tor: Got service ID pyrtqyiqbwb3rhe7, advertising service pyrtqyiqbwb3rhe7.onion:18333 30 | 2020-07-22T23:52:27Z tor: Cached service private key to /home/standup/.bitcoin/testnet3/onion_private_key 31 | ``` 32 | 33 | ## Restablezca su dirección de cebolla RPC 34 | 35 | Si desea restablecer su dirección de cebolla para el acceso RPC, de manera similar borre el `HiddenServiceDirectory` apropiado y reinicie Tor: 36 | ``` 37 | $ sudo rm -rf /var/lib/tor/standup/ 38 | $ sudo /etc/init.d/tor restart 39 | ``` 40 | 41 | > :warning: **ADVERTENCIA:** Restablecer su dirección de cebolla RPC desconectará cualquier billetera móvil u otros servicios que haya conectado usando la API de Quicklink. Haga esto con extrema precaución. 42 | 43 | ## Forzar el uso de Tor para `bitcoind` 44 | 45 | Finalmente, puede forzar el uso de Tor `bitcoind` agregando lo siguiente a su bitcoin.conf: 46 | ``` 47 | proxy=127.0.0.1:9050 48 | listen=1 49 | bind=127.0.0.1 50 | onlynet=onion 51 | ``` 52 | Luego, deberá agregar nodos de semillas basados en cebolla u otros nodos a su configuración, una vez más editando `bitcoin.conf`: 53 | ``` 54 | seednode=address.onion 55 | seednode=address.onion 56 | seednode=address.onion 57 | seednode=address.onion 58 | addnode=address.onion 59 | addnode=address.onion 60 | addnode=address.onion 61 | addnode=address.onion 62 | ``` 63 | Luego, reinicie `tor` y `bitcoind`. 64 | 65 | Ahora debería comunicarse exclusivamente en Tor. Pero, a menos que se encuentre en un estado hostil, este nivel de anonimato probablemente no sea necesario. 66 | Tampoco es particularmente recomendable: puede disminuir en gran medida su número de pares potenciales, provocando problemas de censura o incluso de correlación. 67 | También puede ver un retraso. Y esta configuración puede darle una falsa sensación de anonimato que realmente no existe en la red Bitcoin. 68 | 69 | > :warning: **ADVERTENCIA:** Esta configuración no está probada! ¡Úselo bajo su propio riesgo! 70 | 71 | ## Resumen: cambio de los servicios ocultos de Bitcoin 72 | 73 | Probablemente no necesitará engañar con sus servicios de Onion una vez que los haya verificado, pero en caso de que lo haga, aquí le mostramos cómo restablecer una dirección de Tor que se ha visto comprometida o pasar al uso exclusivo de Tor para su `bitcoind`. 74 | 75 | ## Que sigue? 76 | 77 | Continue "Entendiendo Tor" con [14.3: Agregando Servicios SSH Ocultos](14_3_Agregando_Servicios_SSH_Ocultos.md). 78 | -------------------------------------------------------------------------------- /es/14_3_Agregando_Servicios_SSH_Ocultos.md: -------------------------------------------------------------------------------- 1 | # Capítulo 14.3: Agregar servicios ocultos SSH 2 | 3 | > :information_source: **NOTE:** Esta sección se ha agregado recientemente al curso y es un borrador inicial que aún puede estar pendiente de revisión. Lectura con advertencias. 4 | 5 | Hasta la fecha, ha usado Tor con sus servicios de Bitcoin, pero también puede usarlo para proteger otros servicios en su máquina, mejorando su seguridad y privacidad. Esta sección demuestra cómo mediante la introducción de un servicio `ssh` oculto para iniciar sesión de forma remota usando Tor. 6 | 7 | ## Crear servicios ocultos SSH 8 | 9 | Los nuevos servicios se crean agregándolos al archivo `/etc/tor/torrc`: 10 | ``` 11 | $ su 12 | # cat >> /etc/tor/torrc << EOF 13 | HiddenServiceDir /var/lib/tor/hidden-service-ssh/ 14 | HiddenServicePort 22 127.0.0.1:22 15 | EOF 16 | # exit 17 | ``` 18 | Esto es lo que eso significa: 19 | 20 | * HiddenServiceDir: Indica que tiene un directorio de servicio oculto con la configuración necesaria en esta ruta. 21 | * HiddenServicePort: Indica el puerto tor que se utilizará; en el caso de SSH, suele ser 22. 22 | 23 | Después de agregar las líneas apropiadas a su archiv `torrc`, deberá reiniciar Tor: 24 | 25 | ``` 26 | $ sudo /etc/init.d/tor restart 27 | ``` 28 | Después del reinicio, su directorio `HiddenServiceDir` debería tener nuevos archivos de la siguiente manera: 29 | ``` 30 | $ sudo ls -l /var/lib/tor/hidden-service-ssh 31 | total 16 32 | drwx--S--- 2 debian-tor debian-tor 4096 Jul 22 14:55 authorized_clients 33 | -rw------- 1 debian-tor debian-tor 63 Jul 22 14:56 hostname 34 | -rw------- 1 debian-tor debian-tor 64 Jul 22 14:55 hs_ed25519_public_key 35 | -rw------- 1 debian-tor debian-tor 96 Jul 22 14:55 hs_ed25519_secret_key 36 | ``` 37 | El archivo `hostname` de este directorio contiene su nueva identificación de cebolla: 38 | ``` 39 | $ sudo cat /var/lib/tor/hidden-service-ssh/hostname 40 | qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion 41 | ``` 42 | Puede conectarse al `ssh` servicio oculto usando `torify` y esa dirección: 43 | ``` 44 | $ torify ssh standup@qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion 45 | The authenticity of host 'qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion (127.42.42.0)' can't be established. 46 | ECDSA key fingerprint is SHA256:LQiWMtM8qD4Nv7eYT1XwBPDq8fztQafEJ5nfpNdDtCU. 47 | Are you sure you want to continue connecting (yes/no)? yes 48 | Warning: Permanently added 'qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion' (ECDSA) to the list of known hosts. 49 | standup@qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion's password: 50 | ``` 51 | ## Resumen: Agregar servicios ocultos SSH 52 | 53 | Ahora que tiene Tor instalado y sabe cómo usarlo, puede agregar otros servicios a Tor. Simplemente agregue líneas a su `torrc` (en su servidor), luego conéctese con `torify` (en su cliente). 54 | 55 | > :fire: ***¿Cuál es el poder de otros servicios ocultos?*** Cada vez que accede a un servicio en su servidor de forma remota, deja huellas en la red. Incluso si los datos están encriptados por algo como SSH (o TLS), los merodeadores en la red pueden ver desde dónde se está conectando, a dónde se está conectando y qué servicio está utilizando. ¿Importa esto? Esta es la pregunta que debe hacer. Pero si la respuesta es "Sí", puede proteger la conexión con un servicio oculto. 56 | 57 | 58 | ## ¿Que sigue? 59 | 60 | Para un tipo diferente de privacidad pase a "Usando i2p" en el [Capítulo quince](15_0_Usando_i2p.md). 61 | 62 | O, si lo prefiere, hay dos caminos alternativos: 63 | 64 | Si desea mantenerse enfocado en Bitcoin, continúe con "Programación con RPC" con [Capítulo 16: Hablar con Bitcoind con C](16_0_Hablando_a_Bitcoind_con_C.md). 65 | 66 | O, si no es un programador, puede pasar al [Capítulo 19: Entendiendo la configuración de Lightning](19_0_Entendiendo_Su_Configuracion_Lightning.md) para continuar con su educación de línea de comandos con la red Lightning. 67 | -------------------------------------------------------------------------------- /es/15_0_Usando_i2p.md: -------------------------------------------------------------------------------- 1 | # Capítulo 15: Usando i2p 2 | 3 | El Proyecto Internet Invisible (I2P) es una capa de red totalmente encriptada. Esta usa una [base de datos](https://geti2p.net/en/docs/how/network-database) distribuida y túneles unidireccionales encriptados entre usted y sus pares. 4 | 5 | Diferencias básicas entre Tor y i2p: 6 | 7 | | | Tor | i2p | 8 | | :--- | :---: | ---: | 9 | | Enrutamiento | [Onion](https://www.onion-router.net/) | [Garlic](https://geti2p.net/en/docs/how/garlic-routing) | 10 | | Base de Datos de Red | [Servidores Directorio](https://blog.torproject.org/possible-upcoming-attempts-disable-tor-network) de confianza | [Base de Datos de Red Distribuida](https://geti2p.net/en/docs/how/network-database) | 11 | | Retransmisión | Conexiones encriptadas **bidireccionales** entre cada Retransmisor | Conexiones **unidireccionales** entre cada servidor con sus túneles | 12 | | Servicios Ocultos | Lento | Rápido | 13 | 14 | Lea más: https://geti2p.net/en/comparison/tor 15 | 16 | Este no es instalado por [Bitcoin Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts) actualmente ya que el soporte i2p fue agregado a Bitcoin Core recientemente. Sin embargo, puede probarlo manualmente siguiendo los pasos mencionados en la [Sección Uno](15_1_Servicio_i2p.md). 17 | 18 | ## Objetivos para Este Capítulo 19 | 20 | Después de procesar este capitulo, un desarrollador sera capaz de: 21 | 22 | * Ejecutar Bitcoin Core como un servicio I2P (Proyecto Internet Invisible) 23 | 24 | Los objetivos de apoyo incluyen la habilidad de: 25 | 26 | * Entender la red i2p 27 | * Entender las diferencias entre Tor e i2p 28 | 29 | ## Tabla de Contenidos 30 | 31 | * [Sección Uno: Bitcoin Core como un Servicio I2P (Proyecto Internet Invisible)](15_1_Servicio_i2p.md) 32 | -------------------------------------------------------------------------------- /es/16_0_Hablando_a_Bitcoind_con_C.md: -------------------------------------------------------------------------------- 1 | # Capítulo 16: Hablar con Bitcoind con C 2 | 3 | Mientras trabajamos con Bitcoin Scripts, llegamos a los límites de lo que es posible con bitcoin-cli: actualmente no se puede usar para generar transacciones que contengan scripts inusuales. Los scripts de Shell tampoco son buenos para algunas cosas, como la creación de programas de escucha que sondean constantemente. Afortunadamente, existen otras formas de acceder a la red Bitcoin: API de programación. 4 | 5 | Esta sección se centra en tres bibliotecas diferentes que pueden usarse como base de la programación C sofisticada: una biblioteca RPC y una biblioteca JSON juntas le permiten recrear mucho de lo que hizo en scripts de shell, pero ahora usando C; mientras que una biblioteca ZMQ lo vincula a notificaciones, algo a lo que no ha podido acceder anteriormente. (El próximo capítulo cubrirá una biblioteca aún más sofisticada llamada Libwally, para terminar este vistazo introductorio a la programación de Bitcoin con C.) 6 | 7 | ## Objetivos de este capítulo 8 | 9 | Después de trabajar en este capítulo, un desarrollador podrá: 10 | 11 | * Crear programas en C que usen RPC para hablar con Bitcoind 12 | * Crear programas en C que usen ZMQ para hablar con Bitcoind 13 | 14 | Los objetivos de apoyo incluyen la capacidad de: 15 | 16 | * Comprender cómo usar una biblioteca RPC 17 | * Comprender cómo usar una biblioteca JSON 18 | * Comprender las capacidades de ZMQ 19 | * Comprender cómo usar una biblioteca ZMQ 20 | 21 | ## Tabla de contenido 22 | 23 | * [Sección uno: Acceso a Bitcoind en C con bibliotecas RPC](16_1_Accediendo_a_Bitcoind_en_C_con_las_Bibliotecas_RPC.md) 24 | * [Sección dos: Programación de Bitcoind en C con bibliotecas RPC](16_2_Programando_Bitcoind_en_C_con_las_Bibliotecas_RPC.md) 25 | * [Sección tres: Recibir notificaciones en C con bibliotecas ZMQ](16_3_Recibiendo_Notificaciones_de_Bitcoind_en_C_con_las_Bibliotecas_ZMQ.md) 26 | -------------------------------------------------------------------------------- /es/17_0_Programando_Bitcoin_con_Libwally.md: -------------------------------------------------------------------------------- 1 | # Capítulo 17: Programación con Libwally 2 | 3 | El capítulo anterior presentó tres Bibliotecas C, para RPC, JSON y ZMQ, todas las cuales están destinadas a interactuar directamente con `bitcoind`, tal como lo ha estado haciendo desde el principio. Pero a veces es posible que desee codificar sin acceso directo a un `bitcoind`. Esto puede ser debido a un cliente fuera de línea, o simplemente porque desea mantener alguna funcionalidad interna en su programa C. También es posible que desee entrar en una funcionalidad de cartera más profunda, como la creación de palabras mnemónicas o la derivación de direcciones. Ahí es donde entra Libwally: es una biblioteca de carteras para C, C++, Java, NodeJS o Python, con envolturas también disponibles para otros idiomas, como Swift. 4 | Este capítulo toca la funcionalidad posible dentro de Libwally, la mayoría de los cuales complementan el trabajo que ha hecho a través del acceso RPC a `bitcoind`, pero algunos de los cuales lo replican. También muestra cómo integrar ese trabajo con los clientes RPC con los que está más familiarizado. Sin embargo, tenga en cuenta que esta es sólo la introducción más cruda a Libwally. Varios de sus conjuntos de funciones más importantes están resaltados, pero nunca hacemos más que meter los dedos del pie. Si encuentra sus funciones útiles o intrigantes, entonces tendrá que profundizar mucho más de lo que este curso puede cubrir. 5 | 6 | ## Objetivos para este capítulo 7 | 8 | Después de trabajar en este capítulo, un desarrollador podrá: 9 | 10 | * Utilizar funciones de cartera con Libwally 11 | * Realizar manipulaciones de PSBTs y transacciones con Libwally 12 | * Implementar diseños que mezclen Libwally y trabajo RPC 13 | 14 | Los objetivos de apoyo incluyen la capacidad de: 15 | 16 | * Entender las palabras mnemónicas de BIP39 17 | * Conozca más sobre las carteras jerárquicas BIP32 18 | * Resumir la profundidad funcional de Libwally 19 | 20 | ## Tabla de contenidos 21 | * [Sección Uno: Configuración de Libwally](17_1_Configurando_Libwally.md) 22 | * [Sección Dos: Usar BIP39 en Libwally](17_2_Usando_BIP39_en_Libwally.md) 23 | * [Sección Tres: Usar BIP32 en Libwally](17_3_Usando_BIP32_en_Libwally.md) 24 | * [Sección Cuatro: Uso de PSBTs en Libwally](17_4_Usando_PSBTs_en_Libwally.md) 25 | * [Sección Cinco: Usar scripts en Libwally](17_5_Usando_Scripts_en_Libwally.md) 26 | * [Sección Seis: Usar otras funciones en Libwally](17_6_Usando_Otras_Funciones_en_Libwally.md) 27 | * [Sección Siete: Integración de Libwally y Bitcoin-CLI](17_7_Integrando_Libwally_y_Bitcoin-CLI.md) 28 | -------------------------------------------------------------------------------- /es/18_0_Hablando_a_Bitcoind_con_Otros_Lenguajes.md: -------------------------------------------------------------------------------- 1 | # Capítulo 18: Hablando con Bitcoind con otros lenguajes 2 | 3 | Ahora debería tener una base sólida para trabajar con Bitcoin en C, no solo usando bibliotecas RPC, JSON y ZMQ para interactuar directamente con `bitcoind`, sino también utilizando las bibliotecas Libwally para complementar ese trabajo. Y C es un gran lenguaje para la creación de prototipos y la abstracción pero probablemente no es en lo que usted esta programando. Este capítulo por lo tanto toma un recorrido de torbellino de otros seis lenguajes de programación, demostrando la funcionalidad de Bitcoin más básica en cada uno y permitiéndole ampliar las lecciones de la línea de comandos y C al lenguaje de programación de su elección. 4 | Cada una de las secciones contiene aproximadamente la misma información, centrada en: crear una conexión RPC; examinar la cartera; crear una nueva dirección, y crear una transacción. Sin embargo, hay cierta variedad entre los idiomas, mostrando diferentes aspectos de los comandos RPC de Bitcoin en diferentes ejemplos. En particular, algunos lenguajes utilizan la sencilla metodología de `sendtoaddress` mientras que otros utilizan la dura metodología de crear una transacción en bruto desde cero. 5 | 6 | ## Objetivos para este capítulo 7 | 8 | Después de trabajar en este capítulo, un desarrollador podrá: 9 | 10 | * Preparar los entornos de desarrollo de Bitcoin para una variedad de lenguajes 11 | * Utilizar las funciones de la cartera en una variedad de lenguajes 12 | * Usar funciones de transacción en una variedad de lenguajes 13 | 14 | Los objetivos de apoyo incluyen la capacidad de: 15 | 16 | * Entender más sobre Bitcoin RPC a través de interacciones con una variedad de lenguajes 17 | 18 | ## Tabla de contenidos 19 | * [Sección Uno: Acceso a Bitcoind con Go](18_1_Accediendo_a_Bitcoind_con_Go.md) 20 | * [Sección Dos: Acceso a Bitcoind con Java](18_2_Accediendo_a_Bitcoind_con_Java.md) 21 | * [Sección Tres: Acceso a Bitcoind con NodeJS](18_3_Accediendo_a_Bitcoind_con_NodeJS.md) 22 | * [Sección Cuatro: Acceder a Bitcoind con Python](18_4_Accediendo_a_Bitcoind_con_Python.md) 23 | * [Sección Cinco: Acceso a Bitcoind con Rust](18_5_Accediendo_a_Bitcoind_con_Rust.md) 24 | * [Sección Seis: Acceso a Bitcoind con Swift](18_6_Accediendo_a_Bitcoind_con_Swift.md) 25 | -------------------------------------------------------------------------------- /es/19_0_Entendiendo_Su_Configuracion_Lightning.md: -------------------------------------------------------------------------------- 1 | # Capítulo 19: Entendiendo la configuración de Lightning 2 | 3 | > :information_source: **NOTA:** Este es un borrador en progreso, por lo que puedo obtener algunos comentarios de los primeros revisores. Todavía no está listo para aprender. 4 | 5 | El capítulo anterior concluyó nuestro trabajo con Bitcoin propiamente dicho, a través de CLI, scripting y lenguajes de programación. 6 | Sin embargo, hay muchas otras utilidades dentro del ecosistema de Bitcoin: este capítulo y el siguiente cubren lo que puede ser el más grande e importante: Lightning Network. 7 | Aquí comenzará a trabajar con la interfaz de línea de comandos `lightning-cli`, entendiendo la configuración de c-lightning y sus características, incluidos algunos ejemplos y la configuración básica. 8 | 9 | ## Objetivos de este capítulo 10 | 11 | Después de trabajar en este capítulo, un desarrollador podrá: 12 | 13 | * Evaluar que un nodo c-lightning está instalado y actualizado 14 | * Realizar comandos básicos de billetera Lightning 15 | * Crea un canal de Lightning 16 | 17 | Los objetivos de apoyo incluyen la capacidad de: 18 | 19 | * Comprender la configuración básica de Lightning 20 | * Comprender la interacción de los nodos Lightning 21 | * Entender cómo usasr Lightning 22 | 23 | ## Tabla de contenido 24 | 25 | * [Sección uno: Verificación de la configuración de c-lightning](19_1_Verificando_Su_Configuracion_Lightning.md) 26 | * [Sección dos: Conozca su configuración de c-lightning](19_2_Conociendo_Su_Configuracion_Lightning.md) 27 | * [Interludio: Acceso a un segundo nodo Lightning](19_2_Interludio_Accediendo_a_un_Segundo_Nodo_Lightning.md) 28 | * [Sección tres: Creación de un canal Lightning](19_3_Creando_un_Canal_en_Lightning.md) 29 | 30 | 31 | -------------------------------------------------------------------------------- /es/20_0_Usando_Lightning.md: -------------------------------------------------------------------------------- 1 | # Capítulo Veinte: Usando Lightning 2 | 3 | > :information_source: **NOTA:** Este es un borrador en progreso, por lo que puedo obtener algunos comentarios de los primeros revisores. Todavía no está listo para aprender. 4 | 5 | En este capítulo, continuará trabajando con la interfaz de línea de comandos `lightning-cli`. Creará facturas, realizará pagos y cerrará canales — todas las actividades principales para usar Lightning. 6 | 7 | ## Objetivos de Este Capítulo 8 | 9 | Después de trabajar en este capítulo, un desarrollador podrá: 10 | 11 | * Realice pagos en Lightning Network 12 | * Aplicar cierre a un canal Lightning. 13 | 14 | Los objetivos de apoyo incluyen la capacidad de: 15 | 16 | * Comprender el formato de las facturas. 17 | * Comprender el ciclo de vida de los pagos de Lightning Network. 18 | * Sepa cómo expandir la Lightning Network. 19 | 20 | ## Tabla de Contenido 21 | 22 | * [Sección Uno: Generación de una Solicitud de Pago](20_1_Generando_una_Solicitud_de_Pago.md) 23 | * [Sección Dos: Pagar una Factura](20_2_Pagando_una_Factura.md) 24 | * [Sección Tres: Cerrar un Canal Lightning](20_3_Cerrando_un_Canal_Lightning.md) 25 | * [Sección Cuatro: Expandiendo la Red Lightning](20_4_Expandiendo_la_Red_Lightning.md) 26 | -------------------------------------------------------------------------------- /es/A0_Apendices.md: -------------------------------------------------------------------------------- 1 | # Apéndices 2 | 3 | El cuerpo principal de este curso sugiere una configuración bastante estándar 4 | para hacer pruebas con Bitcoin. Lo que sigue en estos apéndices es una mejor 5 | explicación de la configuración y otras opciones de alternativas. 6 | 7 | ## Objetivos para esta sección 8 | 9 | Después de trabajar en este capítulo, un desarrollador podrá: 10 | 11 | * Decidir entre múltiples métodos para crear una cadena de bloques Bitcoin. 12 | 13 | Los objetivos de apoyo incluyen la capacidad de: 14 | 15 | * Entender la configuración de inicio de Bitcoin 16 | * Realizar una compilación de Bitcoin a mano 17 | * Entender el poder de Regtest 18 | * Utilizar el entorno Regtest 19 | 20 | ## Tabla de Contenido 21 | 22 | * [Apéndice Uno: Entendiendo la Configuración Inicial de Bitcoin](A1_0_Entendiendo_Bitcoin_Standup.md) 23 | * [Apéndice Dos: Compilando Bitcoin desde la Fuente](A2_0_Compilando_Bitcoin_desde_la_Fuente.md) 24 | * [Apéndice Tres: Usando Bitcoin Regtest](A3_0_Usando_Bitcoin_Regtest.md) 25 | -------------------------------------------------------------------------------- /es/A1_0_Entendiendo_Bitcoin_Standup.md: -------------------------------------------------------------------------------- 1 | # Apéndice I: Entendiendo la Configuración Inicial de Bitcoin 2 | 3 | [§2.1: Configurando un VPS Bitcoin-Core con Bitcoin-Standup](02_1_Configurando_un_Bitcoin-Core_VPS_con_StackScript.md) 4 | explica el proceso de crear un nodo Bitcoin usando 5 | [Bitcoin-Standup-Scripts](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts). 6 | El siguiente apéndice explica que hacen las principales secciones del programa. 7 | Usted puede querer seguir junto con 8 | [Linode Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts/blob/master/Scripts/LinodeStandUp.sh) 9 | en otra ventana. 10 | 11 | ## Paso 1: Nombre del host 12 | 13 | Su nombre de host es almacenado en `/etc/hostname` y configurado con el comando 14 | `hostname`. También aparece en `/etc/hosts`. 15 | 16 | ## Paso 2: Zona horaria 17 | 18 | La zona horaria de su host es almacenada en `/etc/timezone`, luego un archivo 19 | apropiado es copiado desde `/usr/share/zoneinfo/` a `/etc/localtime`. 20 | 21 | ## Paso 3: Actualizando Debian 22 | 23 | El gestor de paquetes `apt-get` es usado para actualizar su maquina e instalar 24 | `gnupg`, el generador de números aleatorios `haveged`, y el cortafuegos simple 25 | `ufw`. 26 | 27 | Su maquina es configurada automáticamente para estar al día con `echo 28 | "unattended-upgrades unattended-upgrades/enable_auto_updates boolean true" | 29 | debconf-set-selections`. 30 | 31 | ## Paso 4: Configurando un usuario 32 | 33 | Un usuario `standup` es creado, el cual sera usado por sus aplicaciones 34 | Bitcoin. Este también tiene permisos `sudo`, permitiéndole tomar acciones 35 | privilegiadas con esta cuenta. 36 | 37 | Si usted suministro una llave SSH, esta le permitirá acceder a su cuenta (de 38 | otra manera, deberá usar una contraseña creada en la configuración). 39 | 40 | Si usted suministro una dirección IP, el acceso `ssh` estará limitado a esa 41 | dirección, según `/etc/hosts.allow`. 42 | 43 | ## Paso 5: Configurando Tor 44 | 45 | Tor es instalado para proveer servicios protegidos (ocultos) para acceder a los 46 | comandos RPC de Bitcoin a través de su servidor. Vea 47 | [§14.1: Verificando Su Configuración Tor](14_1_Verificando_Su_Configuracion_Tor.md) 48 | para mas información acerca de su configuración Tor. 49 | 50 | Si usted suministro un cliente autorizado para los servicios ocultos, el acceso 51 | estará limitado para esa llave, según 52 | `/var/lib/tor/standup/authorized_clients`. Si usted no lo hizo, 53 | [§14.2](14_2_Cambiando_Sus_Servicios_Bitcoin_Ocultos.md) explica como hacerlo 54 | luego. 55 | 56 | ## Paso 6: Instalando Bitcoin 57 | 58 | Bitcoin es instalado en `~standup/.bitcoin`. Su configuración es almacenada en 59 | `~standup/.bitcoin/bitcoin.conf`. 60 | 61 | Asegúrese que las sumas de comprobación verifiquen según 62 | [§2.1](02_1_Configurando_un_Bitcoin-Core_VPS_con_StackScript.md), de otra 63 | manera, podría estar expuesto a ataques de la cadena de suministro. 64 | 65 | ## Paso 7: Instalando codificador QR 66 | 67 | Para mantener todo compatible con 68 | [GordianSystem](https://github.com/BlockchainCommons/GordianSystem), un código 69 | QR es creado en `/qrcode.png`. Esto puede leerse desde un cliente QuickConnect, 70 | tal como 71 | [GordianWallet](https://github.com/BlockchainCommons/GordianWallet-iOS) 72 | 73 | ## Conclusión — Entendiendo la Configuración Inicial de Bitcoin 74 | 75 | Bitcoin Standup usa programas para probar e imitar mucha de las funcionalidades 76 | de un [GordianNode](https://github.com/BlockchainCommons/GordianNode-macOS). 77 | Este debe proveerlo con un entorno Bitcoin seguro, construido en las bases de 78 | Bitcoin Core y Tor para comunicaciones RPC. 79 | 80 | ## ¿Que sigue? 81 | 82 | Si usted se encontraba en el proceso de crear un nodo Bitcoin para utilizar en 83 | este curso, usted debería volver a 84 | [§2.1](02_1_Configurando_un_Bitcoin-Core_VPS_con_StackScript.md). 85 | 86 | Si usted esta leyendo a través de los apéndices, continúe con 87 | [Apéndice II: Compilando Bitcoin desde la Fuente](A2_0_Compilando_Bitcoin_desde_la_Fuente.md). 88 | -------------------------------------------------------------------------------- /images/README.md: -------------------------------------------------------------------------------- 1 | A directory for images for Learning Bitcoinf from the Command Line 2 | -------------------------------------------------------------------------------- /images/logos/README.md: -------------------------------------------------------------------------------- 1 | This is a standard named directory to contain logos and social-media screens. 2 | -------------------------------------------------------------------------------- /images/logos/lbtc-logo-black.ai: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/logos/lbtc-logo-black.ai -------------------------------------------------------------------------------- /images/logos/lbtc-logo-black.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/logos/lbtc-logo-black.jpg -------------------------------------------------------------------------------- /images/logos/lbtc-logo-black.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/logos/lbtc-logo-black.png -------------------------------------------------------------------------------- /images/logos/lbtc-logo-white.ai: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/logos/lbtc-logo-white.ai -------------------------------------------------------------------------------- /images/logos/lbtc-screen.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/logos/lbtc-screen.jpg -------------------------------------------------------------------------------- /images/logos/lbtc-screen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/logos/lbtc-screen.png -------------------------------------------------------------------------------- /images/logos/lbtc-screen.psd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/logos/lbtc-screen.psd -------------------------------------------------------------------------------- /images/psbt-roles-for-cli-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/psbt-roles-for-cli-1.png -------------------------------------------------------------------------------- /images/psbt-roles-for-cli-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/psbt-roles-for-cli-2.png -------------------------------------------------------------------------------- /images/psbt-roles-for-cli-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/psbt-roles-for-cli-3.png -------------------------------------------------------------------------------- /images/psbt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/images/psbt.png -------------------------------------------------------------------------------- /pt/02_0_Setting_Up_a_Bitcoin-Core_VPS.md: -------------------------------------------------------------------------------- 1 | # Capítulo 2: Configurando um Bitcoin-Core VPS 2 | 3 | Para começar a usar o Bitcoin, primeiro precisamos configurar uma máquina que execute o Bitcoin. Os artigos neste capítulo descrevem como fazer isso, principalmente usando um VPS (Virtual Private Server). 4 | 5 | ## Objetivos deste Capítulo 6 | 7 | Depois de passar por este capítulo, um desenvolvedor será capaz de: 8 | 9 | * Decidir entre os cinco principais tipos de nodes de Bitcoin; 10 | * Criar um node Bitcoin para desenvolvimento; 11 | * Crie uma instância local da Blockchain do Bitcoin. 12 | 13 | Os objetivos secundários incluem a capacidade de: 14 | 15 | * Compreender a configuração da rede básica do VPS; 16 | * Decidir quais prioridades de segurança implementar; 17 | * Entender a diferença entre os nodes prunados e os não prunados; 18 | * Entender a diferença entre nodes Mainnet, Testnet e Regtest; 19 | * Interpretar os fundamentos do arquivo de configuração do Bitcoin. 20 | 21 | ## Tabela de Conteúdo 22 | 23 | Na verdade, não é preciso ler este capítulo inteiro. Decida se gostaria de executar um StackScript para configurar um node em um VPS Linode (§2.2); Ou você deseja configurar em um ambiente diferente, como em uma máquina AWS ou um Mac (§2.3). Em seguida, vá para a seção mais apropriada. Informações adicionais sobre nossas configurações sugeridas também podem ser encontradas no [Apêndice I](A1_0_Understanding_Bitcoin_Standup.md). 24 | 25 | * [Seção Um: Configurando um Bitcoin-Core VPS com Bitcoin Standup](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md) 26 | * [Seção Dois: Configurando uma Máquina Bitcoin-Core de Outras Maneiras](02_2_Setting_Up_Bitcoin_Core_Other.md) -------------------------------------------------------------------------------- /pt/02_2_Setting_Up_Bitcoin_Core_Other.md: -------------------------------------------------------------------------------- 1 | # 2.2: Configurando uma Máquina Bitcoin-Core de Outras Maneiras 2 | 3 | A seção anterior, [§2.1: Configurando um Bitcoin-Core VPS com Bitcoin Standup](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md), assumimos que iríamos criar um full node em um VPS usando um StackScript Linode. Entretanto, podemos querer criar uma instância do Bitcoin Core via qualquer outra metodologia a nossa escolha e ainda assim acompanhar as próximas etapas deste tutorial. 4 | 5 | 6 | A seguir estão outras metodologias de configuração das quais temos conhecimento: 7 | 8 | * *[Compilar da Fonte](A2_0_Compiling_Bitcoin_from_Source.md).* Se preferirmos compilar o Bitcoin Core manualmente, a maneira como fazer isso é discutida no Apêndice 2. 9 | * *[Usando GordianNode-macOS](https://github.com/BlockchainCommons/GordianNode-macOS).* Se possuirmos um Mac moderno, podemos usar o aplicativo *GordianNode* da Blockchain Commons, que é capacitado pelo *BitcoinStandup*, para instalar um full node nosso Mac. 10 | * *[Usando Outros Scripts de Bitcoin Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts).* A Blockchain Commons também oferece uma versão do script Linode que usamos que pode ser executada pela linha de comando em qualquer máquina Debian ou Ubuntu. Esse tende a ser o script "topo-de-linha", o que significa que terá, mais provavelmente, novas funcionalidades e funções, como a instalação da Lightning. 11 | * *[Configurando um Node Bitcoin na AWS](https://wolfmcnally.com/115/developer-notes-setting-up-a-bitcoin-node-on-aws/).* @wolfmcnally escreveu um tutorial passo-a-passo para a configuração de um Bitcoin Core em um Amazon Web Services (AWS). 12 | * *[Configurando um Node Bitcoin em uma Raspberry Pi 3](https://medium.com/@meeDamian/bitcoin-full-node-on-rbp3-revised-88bb7c8ef1d1).* Damian Mee explica como configurar um full node headless em um Raspberry Pi 3. 13 | 14 | ## O Que Vem Depois? 15 | 16 | A não ser que queiramos retornar a alguma das outras metodologias de criação de um node Bitcoin Core, devemos: 17 | 18 | * Seguir em frente para o "bitcoin-cli" com o [Capítulo Três: Compreendendo Nossa Configuração do Bitcoin](03_0_Understanding_Your_Bitcoin_Setup.md). 19 | -------------------------------------------------------------------------------- /pt/03_0_Understanding_Your_Bitcoin_Setup.md: -------------------------------------------------------------------------------- 1 | # Capítulo 3: Compreendendo Nossa Configuração do Bitcoin 2 | 3 | Agora que estamos prontos para começar a trabalhar com a interface de linha de comando `bitcoin-cli`. Mas isso requer primeiro que entendamos a configuração do Bitcoin e os recursos da carteira, que é o que será explicado neste capítulo. 4 | 5 | Neste e nos próximos capítulos, presumimos que uma VPS com Bitcoin instalado esteja sendo utilizada, e que iremos executar o `bitcoind`. Também presumimos que estamos conectados à testnet, permitindo o acesso a bitcoins sem usar fundos reais. Podemos fazer isso com Bitcoin Standup em linode.com, como vimos na sessão [2.1: Configurando um Bitcoin-Core VPS com Bitcoin Standup](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md), ou usando os demais métodos, descritos na sessão [2.2: Configurando uma Máquina Bitcoin Core de Outras Maneiras](02_2_Setting_Up_Bitcoin_Core_Other.md). 6 | 7 | ## Objetivos deste Capítulo 8 | 9 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 10 | 11 | * Demonstrar que o node Bitcoin está instalado e atualizado; 12 | * Criar um endereço para receber bitcoins; 13 | * Usar os comandos básicos da carteira; 14 | * Criar um endereço a partir de um descritor. 15 | 16 | Os objetivos secundários incluem a capacidade de: 17 | 18 | * Compreender o layout básico do arquivo Bitcoin; 19 | * Usar comandos informativos básicos; 20 | * Entender o que é um endereço Bitcoin; 21 | * Entender o que é uma carteira; 22 | * Entender como importar endereços. 23 | 24 | ## Tabela de Conteúdo 25 | 26 | * [Seção Um: Verificando Nossa Configuração do Bitcoin](03_1_Verifying_Your_Bitcoin_Setup.md) 27 | * [Seção Dois: Conhecendo Nossa Configuração do Bitcoin](03_2_Knowing_Your_Bitcoin_Setup.md) 28 | * [Seção Três: Configurando Nossa Carteira](03_3_Setting_Up_Your_Wallet.md) 29 | * [Usando Variáveis de Linha de Comando](03_3__Interlude_Using_Command-Line_Variables.md) 30 | * [Seção Quatro: Recebendo uma Transação](03_4_Receiving_a_Transaction.md) 31 | * [Seção Cinco: Compreendendo o Descritor](03_5_Understanding_the_Descriptor.md) -------------------------------------------------------------------------------- /pt/03_3__Interlude_Using_Command-Line_Variables.md: -------------------------------------------------------------------------------- 1 | # Usando Variáveis de Linha de Comando 2 | 3 | A sessão anterior demonstrou vários comandos de linha de comando usados sem ofuscação ou interferência. No entanto, geralmente essa não é a melhor maneira de executar o Bitcoin usando a linha de comando. Como estamos lidando com variáveis longas, complexas e difíceis de serem lidas, é fácil cometer um erro se estivermos copiando essas variáveis (ou, perder alguns satoshis, se as digitarmos manualmente). Como essas variáveis podem significar a diferença entre receber e perder dinheiro quando usarmos a Mainnet, não _queremos_ cometer erros. Por esses motivos, sugerimos enfaticamente o uso de variáveis de linha de comando para salvar endereços, assinaturas ou outras cadeias de informações longas sempre que isso for razoável. 4 | 5 | Se estiver usando `bash`, podemos salvar as informações em uma variável como esta: 6 | ``` 7 | $ VARIABLE=$(command) 8 | ``` 9 | 10 | Esta é uma substituição de um comando simples, o equivalente a `VARIABLE = command`. O comando entre parênteses é executado e, em seguida, atribuído à VARIABLE. 11 | 12 | Para criar um novo endereço, seria assim: 13 | ``` 14 | $ unset NEW_ADDRESS_1 15 | $ NEW_ADDRESS_1=$(bitcoin-cli getnewaddress "" legacy) 16 | ``` 17 | Esses comandos limpam a variável NEW_ADDRESS_1, apenas para ter certeza, e então a preenchem com os resultados do comando `bitcoin-cli getnewaddress`. 18 | 19 | Podemos então usar o comando `echo` do shell para vermos nosso (novo) endereço: 20 | ``` 21 | $ echo $NEW_ADDRESS_1 22 | mi25UrzHnvn3bpEfFCNqJhPWJn5b77a5NE 23 | ``` 24 | Como nosso endereço está em uma variável, agora podemos assinar facilmente uma mensagem para esse endereço, sem nos preocupar em digitar o endereço incorretamente. É claro que também salvaremos essa assinatura em uma variável! 25 | ``` 26 | $ NEW_SIG_1=$(bitcoin-cli signmessage $NEW_ADDRESS_1 "Hello, World") 27 | $ echo $NEW_SIG_1 28 | IPYIzgj+Rg4bxDwCyoPiFiNNcxWHYxgVcklhmN8aB2XRRJqV731Xu9XkfZ6oxj+QGCRmTe80X81EpXtmGUpXOM4= 29 | ``` 30 | O restante deste tutorial usará esse estilo de armazenamento de informações quando for mais prático. 31 | 32 | > :book: ***Quando não é prático usar variáveis de linha de comando?*** Variáveis de linha de comando não são práticas se precisarmos usar as informações em algum lugar diferente da linha de comando. Por exemplo, salvar a assinatura pode não ser útil se tivermos que enviá-la a outra pessoa por e-mail. Além disso, alguns comandos futuros produzirão objetos JSON ao invés de informações simples, e as variáveis não podem ser usadas para capturar essas informações, ao menos não sem um _pouco_ mais de mais trabalho. 33 | 34 | ## Resumo: Usando Variáveis de Linha de Comando 35 | 36 | Variáveis de shell podem ser usadas para manter longas strings, minimizando as chances de erros. 37 | 38 | ## O Que Vem Depois? 39 | 40 | Vamos continuar "Compreendendo Nossa Configuração do Bitcoin" na sessão [3.4: Recebendo uma Transação](03_4_Receiving_a_Transaction.md). -------------------------------------------------------------------------------- /pt/04_0_Sending_Bitcoin_Transactions.md: -------------------------------------------------------------------------------- 1 | # Capítulo 4: Enviando Transações no Bitcoin 2 | 3 | Este capítulo descreve três métodos diferentes para enviar bitcoins para endereços P2PKH normais à partir da linha de comando, usando apenas o ```bitcoin-cli```. 4 | 5 | ## Objetivos deste Capítulo 6 | 7 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 8 | 9 | * Decidir como enviar dinheiro usando o Bitcoin; 10 | * Criar uma transação bruta; 11 | * Usar aritmética para calcular as taxas. 12 | 13 | Os objetivos secundários incluem a capacidade de: 14 | 15 | * Compreender transações e taxas de transação; 16 | * Entender as transações ```legacy``` e ```SegWit```; 17 | * Usar métodos básicos para enviar dinheiro; 18 | * Usar métodos de cálculo de taxa automática para enviar dinheiro; 19 | * Entender os perigos de transações brutas. 20 | 21 | ## Tabela de Conteúdo 22 | 23 | * [Seção 1: Enviando Moedas da Maneira Fácil](04_1_Sending_Coins_The_Easy_Way.md) 24 | * [Seção 2: Criando uma Transação Bruta](04_2_Creating_a_Raw_Transaction.md) 25 | * [Prefácio: Usando JQ](04_2__Interlude_Using_JQ.md) 26 | * [Seção 3: Criando uma Transação Bruta com Argumentos Nomeados](04_3_Creating_a_Raw_Transaction_with_Named_Arguments.md) 27 | * [Seção 4: Enviando Moedas com Transações Brutas](04_4_Sending_Coins_with_a_Raw_Transaction.md) 28 | * [Seção 5: Enviando Moedas com Transações Brutas Automatizadas](04_5_Sending_Coins_with_Automated_Raw_Transactions.md) 29 | * [Seção 6: Criando uma Transação SegWit](04_6_Creating_a_Segwit_Transaction.md) -------------------------------------------------------------------------------- /pt/05_0_Controlling_Bitcoin_Transactions.md: -------------------------------------------------------------------------------- 1 | # Capítulo 5: Controlando Transações no Bitcoin 2 | 3 | O envio de uma transação nem sempre termina com um "viveram felizes para sempre". Usando os protocolos RBF (Replace-By-Fee, ou Substituindo-A -Taxa no português) e CPFP (Child-Pays-For-Parent, ou Filho-Paga-Pelo-Pai), um desenvolvedor pode continuar a controlar a transação após ela ter sido enviada, para melhorar a eficiência ou para recuperar transações que estava presas na _mempool_. Esses métodos irão começar a mostrar o verdadeiro poder do Bitcoin. 4 | 5 | ## Objetivos deste Capítulo 6 | 7 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 8 | 9 | * Decidir se o RBF ou o CPFP pode ajudar uma transação; 10 | * Criar uma transação de substituição usando o RBF; 11 | * Criar novas transações usando o protocolo CPFP. 12 | 13 | Os objetivos secundários do capítulo incluem a capacidade de: 14 | 15 | * Entender a Mempool; 16 | * Entender a diferença entre o RBF e o CPFP; 17 | * Planejar a taxa do RBF. 18 | 19 | ## Tabela de Conteúdo 20 | 21 | * [Seção 1: Atentando-se para Transações Presas](05_1_Watching_for_Stuck_Transactions.md) 22 | * [Seção 2: Reenviando uma Transação com RBF](05_2_Resending_a_Transaction_with_RBF.md) 23 | * [Seção 3: Financiando uma Transação com CPFP](05_3_Funding_a_Transaction_with_CPFP.md) -------------------------------------------------------------------------------- /pt/06_0_Expanding_Bitcoin_Transactions_Multisigs.md: -------------------------------------------------------------------------------- 1 | # Capítulo 6: Expandindo Transações no Bitcoin com Multisigs 2 | 3 | Transações básicas no Bitcoin: (1) enviam fundos; (2) para um único destinatário P2PKH ou SegWit; (3) de uma única máquina; (4) imediatamente. No entanto, todas as quatro partes desta definição podem ser expandidas usando transações mais complexas no Bitcoin. Este primeiro capítulo sobre "Expansão" mostra como variar os pontos (2) e (3) enviando saldos para um endereço que representa vários destinatários (ou, pelo menos, vários assinantes). 4 | 5 | ## Objetivos deste Capítulo 6 | 7 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 8 | * Criar endereços de Bitcoin multi-assinatura (multisig) usando os fundamentos do Bitcoin; 9 | * Criar endereços de Bitcoin multi-assinatura (multisig) usando mecanismos mais fáceis. 10 | 11 | Os objetivos secundários do capítulo incluem a capacidade de: 12 | * Entender como gastar fundos enviados para um multisig; 13 | * Planejar para obter o máximo do poder dos multisigs. 14 | 15 | ## Tabela de Conteúdo 16 | 17 | * [Seção 1: Enviando uma Transação com Multsig](06_1_Sending_a_Transaction_to_a_Multisig.md) 18 | * [Seção 2: Gastando uma Transação com Multsig](06_2_Spending_a_Transaction_to_a_Multisig.md) 19 | * [Seção 3: Enviando & Gastando um Multisig Automatizado](06_3_Sending_an_Automated_Multisig.md) -------------------------------------------------------------------------------- /pt/07_0_Expanding_Bitcoin_Transactions_PSBTs.md: -------------------------------------------------------------------------------- 1 | # Capítulo Sete: Expandindo Transações no Bitcoin com PSBTs 2 | 3 | No capítulo anterior, discutimos como usar os multisigs para determinar colaborativamente o consentimento entre várias partes. Essa não é a única forma de colaborar na criação de transações no Bitcoin. Os PSBTs são uma tecnologia muito mais recente que permite que colaboremos em vários estágios, incluindo a criação, financiamento e autenticação de uma transação Bitcoin. 4 | 5 | ## Objetivos para Esta Seção 6 | 7 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 8 | 9 | * Criar transações com PSBTs; 10 | * Usas ferramentas da linha de comando para completar PSBTs; 11 | * Usar o HWI para interagir com uma hardware wallet. 12 | 13 | Os objetivos secundários do capítulo incluem a capacidade de: 14 | 15 | * Entender como os PSBTs diferem dos multisig; 16 | * Compreender completamente o fluxo de trabalho com os PSBTs; 17 | * Planejar para todo o poder dos PSBTs; 18 | * Compreender o uso de uma hardware wallet. 19 | 20 | ## Tabela de Conteúdo 21 | 22 | * [Seção Um: Criando uma Transação Parcialmente Assinada no Bitcoin (PSBT)](07_1_Creating_a_Partially_Signed_Bitcoin_Transaction.md) 23 | * [Seção Dois: Usando uma Transação Parcialmente Assinada no Bitcoin (PSBT)](07_2_Using_a_Partially_Signed_Bitcoin_Transaction.md) 24 | * [Seção Três: Integrando com Hardware Wallets](07_3_Integrating_with_Hardware_Wallets.md) -------------------------------------------------------------------------------- /pt/08_0_Expanding_Bitcoin_Transactions_Other.md: -------------------------------------------------------------------------------- 1 | # Capítulo 8: Expandindo Transações no Bitcoin de Outras Maneiras 2 | 3 | A definição de transações básicas descrita no [Capítulo Seis](06_0_Expanding_Bitcoin_Transactions_Multisigs.md) diz que enviamos os _fundos_ _imediatamente_, mas esses são os dois elementos que podem ser alterados. Esta seção final sobre _Expandindo transações de Bitcoin_ fala sobre como enviar coisas que não sejam moedas e como fazer isso em um momento diferente do atual. 4 | 5 | ## Objetivos deste Capítulo 6 | 7 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 8 | 9 | * Criar transações com Locktimes; 10 | * Criar transações com dados. 11 | 12 | Os objetivos secundários incluem a capacidade de: 13 | 14 | * Compreender os diferentes tipos de Timelocks; 15 | * Planejar usando o poder do Locktime; 16 | * Planejar usando o poder de OP_RETURN. 17 | 18 | ## Tabela de Conteúdo 19 | 20 | * [Seção Um: Enviando uma Transação com um Locktime](08_1_Sending_a_Transaction_with_a_Locktime.md) 21 | * [Seção Dois: Enviando uma Transação com Dados](08_2_Sending_a_Transaction_with_Data.md) -------------------------------------------------------------------------------- /pt/09_0_Introducing_Bitcoin_Scripts.md: -------------------------------------------------------------------------------- 1 | # Capítulo 9: Apresentando os Scripts do Bitcoin 2 | 3 | Até o momento, temos interagido com o Bitcoin em um nível relativamente alto de abstração. O programa ```bitcoin-cli``` oferece acesso a uma variedade de comandos RPC que suportam a criação e controle de transações brutas de Bitcoin que incluem saldos, dados, timelocks e multisigs. 4 | 5 | No entanto, o Bitcoin oferece muito mais complexidade do que isso. O software oferece uma linguagem de script simples que pode ser usada para criar condições de resgate ainda mais complexas. Se os multisigs e os timelocks fornecerem as bases para os contratos inteligentes, o script do Bitcoin constrói os alicerces. É o próximo passo para capacitar o Bitcoin. 6 | 7 | ## Objetivos deste Capítulo 8 | 9 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 10 | 11 | * Projetar um script no Bitcoin; 12 | * Aplicar um script no Bitcoin. 13 | 14 | Os objetivos secundários do capítulo incluem a capacidade de: 15 | 16 | * Compreender o propósito dos scripts no Bitcoin; 17 | * Entender os script P2PKH; 18 | * Entender como o P2WPKH funciona com os scripts; 19 | * Compreender as necessidades dos testes dos scripts do bitcoin. 20 | 21 | ## Tabela de Conteúdo 22 | 23 | * [Seção Um: Compreendendo a Base das Transações](09_1_PriveStanding_the_foundation_of_transactions.md) 24 | * [Seção Dois: Executando um Script do Bitcoin](09_2_running_a_bitcoin_script.md) 25 | * [Seção Três: Testando um Script do Bitcoin](09_3_testing_a_bitcoin_script.md) 26 | * [Seção Quatro: Programando um P2PKH](09_4_scripting_a_p2pkh.md) 27 | * [Seção Cinco: Programando um P2WPKH](09_5_scripting_a_p2wpkh.md) -------------------------------------------------------------------------------- /pt/10_0_Embedding_Bitcoin_Scripts_in_P2SH_Transactions.md: -------------------------------------------------------------------------------- 1 | # Capítulo 10: Incorporando Scripts em Transações P2SH no Bitcoin 2 | 3 | O Bitcoin Script desce vários níveis de abstração, permitindo que controlemos minuciosamente as condições de resgate dos fundos. Mas, como realmente incorporamos esses scripts do Bitcoin nas transações que construímos até agora? A resposta é um novo tipo de transação de Bitcoin, o P2SH. 4 | 5 | ## Objetivos deste Capítulo 6 | 7 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 8 | 9 | * Projetar uma transação P2SH; 10 | * Aplicar um script P2SH Bitcoin. 11 | 12 | Os objetivos secundários do capítulo incluem a capacidade de: 13 | 14 | * Compreender o script P2SH; 15 | * Compreender o script Multisig; 16 | * Compreender as várias variações dos scripts Segwit; 17 | * Entender como gastar fundos enviados a um P2SH. 18 | 19 | ## Tabela de Conteúdo 20 | 21 | * [Seção 1: Compreendendo a Base do P2SH](10_1_Understanding_the_Foundation_of_P2SH.md) 22 | * [Seção 2: Construindo a Estrutura do P2SH](10_2_Building_the_Structure_of_P2SH.md) 23 | * [Seção 3: Executando um Script do Bitcoin com P2SH](10_3_Running_a_Bitcoin_Script_with_P2SH.md) 24 | * [Seção 4: Programando um Multisig](10_4_Scripting_a_Multisig.md) 25 | * [Seção 5: Programando um Script Segwit](10_5_Scripting_a_Segwit_Script.md) 26 | * [Seção 6: Gastando uma Transação P2SH](10_6_Spending_a_P2SH_Transaction.md) -------------------------------------------------------------------------------- /pt/10_3_Running_a_Bitcoin_Script_with_P2SH.md: -------------------------------------------------------------------------------- 1 | # 10.3: Executando um Script no Bitcoin com P2SH 2 | 3 | Agora que conhecemos a teoria e a prática por trás dos endereços P2SH, estamos prontos para transformar um script de Bitcoin não-padrão em uma transação real. Vamos utilizar o script de bloqueio simples da seção [§9.2: Executando um Script no Bitcoin](09_2_Running_a_Bitcoin_Script.md), `OP_ADD 99 OP_EQUAL`. 4 | 5 | ## Criando uma Transação P2SH 6 | 7 | Para bloquear uma transação com este script, precisamos fazer o seguinte: 8 | 9 | 1. Serializar o `OP_ADD 99 OP_EQUAL`: 10 | 1. OP_ADD = 0x93 - uma tradução simples do opcode; 11 | 2. 99 = 0x01, 0x63 - este opcode coloca um byte na pilha, 99 (hex: 0x63); 12 | * Não se preocupe com a conversão porque é apenas um byte. 13 | 3. OP_EQUAL = 0x87 - uma tradução simples do opcode; 14 | 4. `````` = "93016387". 15 | 16 | ``` 17 | $ btcc OP_ADD 99 OP_EQUAL 18 | 93016387 19 | ``` 20 | 2. Vamos salvar o `````` para referência futura como ```redeemScript```; 21 | 1. `` = "93016387". 22 | 3. SHA-256 e RIPEMD-160 do hash do script serializado; 23 | 1. `````` = "3f58b4f7b14847a9083694b9b3b52a4cea2569ed". 24 | 4. Produzir um script de bloqueio P2SH que inclua o ``````; 25 | 1. ```scriptPubKey``` ="a9143f58b4f7b14847a9083694b9b3b52a4cea2569ed87". 26 | 27 | Podemos então criar uma transação usando o ```scriptPubKey```, provavelmente através de uma API. 28 | 29 | ## Desbloqueando a Transação P2SH 30 | 31 | Para desbloquear essa transação, é necessário que o destinatário produza um ```scriptSig``` que acrescente duas constantes, totalizando noventa e nove, ao script serializado:```1 98 ```. 32 | 33 | ### Executando a Primeira Rodada de Validação 34 | 35 | O processo de desbloqueio da transação P2SH começa com uma primeira rodada de validação, que nada mais é que a verificação se o script de resgate corresponde ao valor hash no script de bloqueio. 36 | 37 | Vamos concatenar o ```scriptSig``` e o ```scriptPubKey``` e executá-los, normalmente: 38 | ``` 39 | Script: 1 98 OP_HASH160 OP_EQUAL 40 | Stack: [] 41 | 42 | Script: 98 OP_HASH160 OP_EQUAL 43 | Stack: [ 1 ] 44 | 45 | Script: OP_HASH160 OP_EQUAL 46 | Stack: [ 1 98 ] 47 | 48 | Script: OP_HASH160 OP_EQUAL 49 | Stack: [ 1 98 ] 50 | 51 | Script: OP_EQUAL 52 | Running: OP_HASH160 53 | Stack: [ 1 98 ] 54 | 55 | Script: OP_EQUAL 56 | Stack: [ 1 98 ] 57 | 58 | Script: 59 | Running: OP_EQUAL 60 | Stack: [ 1 98 True ] 61 | ``` 62 | O script termina com um ```True``` no topo da pilha e, portanto, foi bem-sucedido... embora haja outro fragmento abaixo dele. 63 | 64 | Porém, por se tratar de um script P2SH, a execução não está concluída. 65 | 66 | ### Executando a Segunda Rodada de Validação 67 | 68 | Para a segunda rodada de validação, vamos verificar se os valores no script de desbloqueio satisfazem o ```redeemScript```: desserializando o ```redeemScript``` ("93016387" = "OP_ADD 99 OP_EQUAL") e executando-o usando os itens no ```scriptSig``` anterior para o script serializado: 69 | 70 | ``` 71 | Script: 1 98 OP_ADD 99 OP_EQUAL 72 | Stack: [ ] 73 | 74 | Script: 98 OP_ADD 99 OP_EQUAL 75 | Stack: [ 1 ] 76 | 77 | Script: OP_ADD 99 OP_EQUAL 78 | Stack: [ 1 98 ] 79 | 80 | Script: 99 OP_EQUAL 81 | Running: 1 98 OP_ADD 82 | Stack: [ 99 ] 83 | 84 | Script: OP_EQUAL 85 | Stack: [ 99 99 ] 86 | 87 | Script: 88 | Running: 99 99 OP_EQUAL 89 | Stack: [ True ] 90 | ``` 91 | Com essa segunda validação _também_ verdadeira, o UTXO agora pode ser gasto! 92 | 93 | ## Resumo: Executando um Script no Bitcoin com P2SH 94 | 95 | Depois de conhecer a técnica de construção dos P2SH, qualquer script pode ser embutido em uma transação Bitcoin, e depois de entender a técnica de validação do P2SH, é fácil executar os scripts em duas fases. 96 | 97 | ## O Que Vem Depois? 98 | 99 | Vamos continuar "Incorporando Scripts em Transações P2SH no Bitcoin" na seção [§10.4: Programando um Multisig](10_4_Scripting_a_Multisig.md). -------------------------------------------------------------------------------- /pt/10_6_Spending_a_P2SH_Transaction.md: -------------------------------------------------------------------------------- 1 | # 10.6: Gastando uma Transação P2SH 2 | 3 | Antes de encerrarmos esta visão geral das transações P2SH, vamos abordar como gastá-las. Esta seção é principalmente uma visão geral, referindo-se a uma seção anterior onde _já_ gastamos uma transação P2SH. 4 | 5 | ## Usando o Script de Resgate 6 | 7 | Como vimos na seção [§6.2: Gastando uma Transação com Multsig](06_2_Spending_a_Transaction_to_a_Multisig.md), gastar uma transação P2SH tem tudo a ver com ter aquela versão serializada do script de bloqueio, o chamado _redeemScript_. Portanto, o primeiro passo para poder gastar uma transação P2SH é ter certeza de salvar o _redeemScript_ antes de fornecer o endereço P2SH para todos. 8 | 9 | ### Coletando as Variáveis 10 | 11 | Como endereços P2SH além dos endereços especiais multisig e nested Segwit não estão integrados no ```bitcoin-cli```, não haverá atalhos para gastarmos o P2SH como vimos na seção [§6.3: Enviando e Gastando um Multisig de Maneira Automatizada](6_3_Sending_an_Automated_Multisig.md) . Vamos precisar coletar todas as variáveis mais complexas por conta própria! 12 | 13 | Isso significa que precisaremos coletar: 14 | 15 | * O ```hex``` do ```scriptPubKey``` para a transação que estamos gastando; 16 | * O ```redeemScript``` serializado; 17 | * Quaisquer chaves privadas, já que assinaremos manualmente; 18 | * Todos os ```txids```,```vouts``` e ```addresses``` regulares que precisarmos. 19 | 20 | ## Criando a Transação 21 | 22 | Como vimos na seção §6.2, a criação de uma transação é bem padrão: 23 | ``` 24 | $ rawtxhex=$(bitcoin-cli -named createrawtransaction inputs='''[ { "txid": "'$utxo_txid'", "vout": '$utxo_vout' } ]''' outputs='''{ "'$recipient'": 0.00005}''') 25 | $ echo $rawtxhex 26 | 020000000121654fa95d5a268abf96427e3292baed6c9f6d16ed9e80511070f954883864b10000000000ffffffff0188130000000000001600142c48d3401f6abed74f52df3f795c644b4398844600000000 27 | ``` 28 | No entanto, a assinatura requer a inserção de informações extras para o (1) ```scriptPubKey```; (2) o ```redeemScript``` e; (3) quaisquer chaves privadas necessárias. 29 | 30 | Aqui está o exemplo de como fazer isso para aquele multisig P2SH integrado na seção §6.2: 31 | ``` 32 | $ bitcoin-cli -named signrawtransactionwithkey hexstring=$rawtxhex prevtxs='''[ { "txid": "'$utxo_txid'", "vout": '$utxo_vout', "scriptPubKey": "'$utxo_spk'", "redeemScript": "'$redeem_script'" } ]''' privkeys='["cNPhhGjatADfhLD5gLfrR2JZKDE99Mn26NCbERsvnr24B3PcSbtR"]' 33 | ``` 34 | Com qualquer outro tipo de P2SH, incluiremos um ```redeemscript``` diferente, mas, fora isso, a prática é exatamente a mesma. A única diferença é que depois de dois capítulos de trabalho com scripts agora entendemos o que é o ```scriptPubKey``` e o que é o ```redeemScript```, então, esperançosamente, o que eram elementos misteriosos a quatro capítulos atrás, agora não são tão misteriosos assim. 35 | 36 | ## Resumo: Gastando uma Transação P2SH 37 | 38 | Já gastamos um P2SH no Capítulo 6, quando reenviamos uma transação multsig da maneira mais difícil, que exigia alinhar as informações do ```scriptPubKey``` e do ```redeemScript```. Agora sabemos que o ```scriptPubKey``` é um script de bloqueio P2SH padronizado, enquanto o ```redeemScript``` corresponde a um hash naquele script de bloqueio e que precisamos ser capazes de executá-lo com as variáveis ​​adequadas para receber um resultado ```True```. Mas além disso, não há nada de novo ao gastar uma transação P2SH, porque já fizemos isso! 39 | 40 | ## O Que Vem Depois? 41 | 42 | Vamos avançar com "Programando Bitcoin" no [Capítulo 11: Capacitando Timelock com Scripts no Bitcoin](11_0_Empowering_Timelock_with_Bitcoin_Scripts.md). -------------------------------------------------------------------------------- /pt/11_0_Empowering_Timelock_with_Bitcoin_Scripts.md: -------------------------------------------------------------------------------- 1 | 2 | # Capítulo 11: Capacitando Timelock com Scripts do Bitcoin 3 | 4 | O recurso ```nLockTime``` da seção [§8.1](08_1_Sending_a_Transaction_with_a_Locktime.md) foi apenas o começo dos Timelocks. Quando começamos a escrever scripts do Bitcoin, dois opcodes de timelocks ficam disponíveis. 5 | 6 | ## Objetivos deste Capítulo 7 | 8 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 9 | 10 | * Decidir qual Timelock usar; 11 | * Criar scripts com CLTV; 12 | * Criar scripts com CSV. 13 | 14 | Os objetivos secundários do capítulo incluem a capacidade de: 15 | 16 | * Compreender as diferenças entre os diferentes timelocks; 17 | * Gerar tempos relativos. 18 | 19 | ## Índice 20 | 21 | * [Seção 1: Compreendendo As Opções de Timelock](11_1_Understanding_Timelock_Options.md) 22 | * [Seção 2: Usando CLTV em Scripts](11_2_Using_CLTV_in_Scripts.md) 23 | * [Seção 3: Usando CSV em Scripts](11_3_Using_CSV_in_Scripts.md) -------------------------------------------------------------------------------- /pt/12_0_Expanding_Bitcoin_Scripts.md: -------------------------------------------------------------------------------- 1 | # Capítulo 12: Expandindo os Scripts do Bitcoin 2 | 3 | Ainda há um pouco mais sobre os Scripts do Bitcoin que precisamos saber. As condicionais fornecem acesso total ao controle de fluxo, enquanto uma variedade de outros opcodes podem expandir nossas possibilidades. 4 | 5 | ## Objetivos Deste Capítulo 6 | 7 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 8 | 9 | * Decidir como usar os condicionais no script; 10 | * Decidir como usar outros opcodes no script. 11 | 12 | Os objetivos secundários do capítulo incluem a capacidade de: 13 | 14 | * Compreender toda a gama de possibilidades de programação; 15 | * Identificar como aprender mais sobre os opcodes. 16 | 17 | ## Tabela de Conteúdo 18 | 19 | * [Seção 1: Usando Condicionais no Script](12_1_Using_Script_Conditionals.md) 20 | * [Seção 2: Usando Outros Comandos no Script](12_2_Using_Other_Script_Commands.md) -------------------------------------------------------------------------------- /pt/12_2_Using_Other_Script_Commands.md: -------------------------------------------------------------------------------- 1 | # 12.2: Usando Outros Comandos no Script 2 | 3 | Provavelmente já temos em mãos a maioria dos opcodes do Bitcoin Script que iremos usar na maioria dos nossos scripts. No entanto, o Bitcoin Script oferece muito mais opções, o que pode vir a ser exatamente o que precisamos para criar o instrumento financeiro dos nossos sonhos. 4 | 5 | Devemos consultar a [página do script do Bitcoin](https://en.bitcoin.it/wiki/script) para termos uma lista mais completa de todos esses e muitos outros comandos. Esta seção destaca apenas os opcodes mais notáveis. 6 | 7 | ## Entendendo os Opcodes Aritméticos 8 | 9 | Os opcodes aritméticos manipulam ou testam números. 10 | 11 | Manipulam um número: 12 | 13 | * OP_1ADD (0x8b) - Adiciona uma unidade; 14 | * OP_1SUB (0x8C) - Subtrai uma unidade; 15 | * OP_NEGATE (0x8f) - Inverte o sinal do número; 16 | * OP_ABS (0x90) - Torna o número positivo; 17 | * OP_NOT (0x91) - Troca 1 por 0, senão 0. 18 | 19 | Veja também: ```OP_0NOTEQUAL``` (0x92). 20 | 21 | Manipulam dois números matematicamente: 22 | 23 | * OP_ADD (0x93) - Adiciona dois números; 24 | * OP_SUB (0x94) - Subtrai dois números; 25 | * OP_MIN (0xA3) - Retorna o menor entre dois números; 26 | * OP_MAX (0xA4) - Retorna o maior entre dois números. 27 | 28 | Manipulam dois números logicamente: 29 | 30 | * OP_BOOLAND (0x9a) - 1 se ambos os números não são 0, senão 0; 31 | * OP_BOOLOR (0x9B) - 1 se qualquer número não é 0, senão 0. 32 | 33 | Testa dois números: 34 | 35 | * OP_NUMEQUAL (0x9C) - 1 se ambos os números forem iguais, senão 0; 36 | * OP_LESSTHAN (0x9f) - 1 se o primeiro número for menor que o segundo, senão 0; 37 | * OP_GREATERTHAN (0xA0) - 1 se o primeiro número for maior que o segundo, senão 0; 38 | * OP_LESSTHANOREQUAL (0xA1) - 1 se o primeiro número for menor ou igual ao segundo, senão 0; 39 | * OP_GREATERTHANOREQUAL (0xA2) - 1 se o primeiro número for maior ou igual a segundo, senão 0. 40 | 41 | Veja também: ```OP_NUMEQUALVERIFY``` (0x9d) e ```OP_NUMNOTEQUAL``` (0x9e) 42 | 43 | Testa três números: 44 | 45 | * OP_WITHIN (0xA5) - 1 se um número estiver no intervalo de dois outros números. 46 | 47 | ## Compreendendo os Opcodes de Pilha 48 | 49 | Há um número chocante de opcodes de pilha, mas além de ```OP_DROP```, ```OP_DUP```, e às vezes ```OP_SWAP```, eles geralmente não serão necessários se tivermos cuidado com a ordem da pilha. No entanto, aqui estão alguns dos mais interessantes: 50 | 51 | * OP_DEPTH (0x74) - Aumenta o tamanho da pilha; 52 | * OP_DROP (0x75) - Retira o item superior da pilha; 53 | * OP_DUP (0x76) - Duplica o item superior da pilha; 54 | * OP_PICK (0x79) - Duplica o enésimo item da pilha começando pelo topo; 55 | * OP_ROLL (0x7a) - Move o enésimo item para o topo da pilha; 56 | * OP_SWAP(0x7C) - Troca os dois principais itens da pilha. 57 | 58 | Veja também: `OP_TOALTSTACK` (0x6b), `OP_FROMALTSTACK` (0x6c), `OP_2DROP` (0x6d), `OP_2DUP` (0x6e), `OP_3DUP` (0x6f), `OP_2OVER` (0x70), `OP_2ROT` (0x71), `OP_2SWAP` (0x72), `OP_IFDUP` (0x73), `OP_NIP` (0x77), `OP_OVER` (0x78), `OP_ROT` (0x7b), e `OP_TUCK` (0x7d). 59 | 60 | ## Compreendendo os Opcodes Criptográficos 61 | 62 | Finalmente, uma variedade de opcodes para dar suporte ao hashing e à verificação de assinatura: 63 | 64 | Hash: 65 | 66 | * OP_RIPEMD160 (0xa6) — RIPEMD-160; 67 | * OP_SHA1 (0xa7) — SHA-1; 68 | * OP_SHA256 (0xa8) - SHA-256; 69 | * OP_HASH160 (0xa9) — SHA-256 + RIPEMD-160; 70 | * OP_HASH256 (0xaa) — SHA-256 + SHA-256. 71 | 72 | Verifica as assinaturas: 73 | 74 | * OP_CHECKSIG (0xac) - Verifica uma assinatura; 75 | * OP_CHECKMULTISIG (0xae) - Verifica um multisig m-de-n. 76 | 77 | Veja também: `OP_CODESEPARATOR` (0xab), `OP_CHECKSIGVERIFY` (0xad), e `OP_CHECKMULTISIGVERIFY` (0xaf). 78 | 79 | ## Resumo: Usando Outros Comandos no Script 80 | 81 | O Bitcoin Script inclui uma ampla gama de opcodes aritméticos, de pilha e criptográficos. A maioria desses opcodes adicionais provavelmente não serão tão comuns quanto os discutidos nas seções anteriores, mas, no entanto, estão disponíveis caso precisemos utilizá-los para escrever nosso script! 82 | 83 | ## O Que Vem Depois? 84 | 85 | Vamos avançar "Expandindo os Scripts do Bitcoin" com o [Capítulo 13: Projetando Scripts Reais no Bitcoin](13_0_Designing_real_bitcoin_scripts.md). -------------------------------------------------------------------------------- /pt/13_0_Designing_Real_Bitcoin_Scripts.md: -------------------------------------------------------------------------------- 1 | # Capítulo 13: Projetando Scripts Reais no Bitcoin 2 | 3 | Até então, nossos scripts no Bitcoin têm sido exemplos teóricos, porque ainda estamos montando as peças do quebra-cabeça. Agora, com o repertório completo do Bitcoin Script em mãos, estamos prontos para nos aprofundarmos em vários scripts do mundo real e ver como eles funcionam. 4 | 5 | ## Objetivos Deste Capítulo 6 | 7 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 8 | 9 | * Avaliar scripts do Bitcoin do mundo real; 10 | * Criar scripts do Bitcoin no mundo real. 11 | 12 | 13 | Os objetivos secundários incluem a capacidade de: 14 | 15 | * Entender os scripts do Bitcoin existentes; 16 | * Compreender a importância das assinaturas. 17 | 18 | ## Tabela de Conteúdo 19 | 20 | * [Seção 1: Escrevendo Scripts de Quebra-Cabeças](13_1_Writing_Puzzle_Scripts.md) 21 | * [Seção 2: Escrevendo Scripts Complexos de Multisig](13_2_Writing_Complex_Multisig_Scripts.md) 22 | * [Seção 3: Capacitando o Bitcoin com Scripts](13_3_Empowering_Bitcoin_with_Scripts.md) -------------------------------------------------------------------------------- /pt/14_0_Using_Tor.md: -------------------------------------------------------------------------------- 1 | # Capítulo 14: Usando o Tor 2 | 3 | O Tor é um dos programas padrão instalados pelo [Bitcoin Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts). Ele nos ajuda a manter nosso servidor seguro, o que é extremamente importante quando estamos lidando com Bitcoin. Este capítulo divaga um pouco do nosso objetivo para nos ajudar a entender essa infraestrutura de segurança. 4 | 5 | ## Objetivos deste Capítulo 6 | 7 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 8 | 9 | * Usar uma configuração Tor; 10 | * Fazer a manutenção do Tor. 11 | 12 | Os objetivos secundários incluem a capacidade de: 13 | 14 | * Compreender a rede Tor; 15 | * Compreender as várias portas do Bitcoin. 16 | 17 | ## Tabela de Conteúdo 18 | 19 | * [Seção 1: Verificando Nossa Configuração do Tor](14_1_Verifying_Your_Tor_Setup.md) 20 | * [Seção 2: Mudando Nossos Serviços Ocultos do Bitcoin](14_2_Changing_Your_Bitcoin_Hidden_Services.md) 21 | * [Seção 3: Adicionando Serviços SSH Ocultos](14_3_Adding_SSH_Hidden_Services.md) -------------------------------------------------------------------------------- /pt/14_3_Adding_SSH_Hidden_Services.md: -------------------------------------------------------------------------------- 1 | # 14.3: Adicionando Serviços SSH Ocultos 2 | 3 | >:information_source: **NOTA:** Esta seção foi adicionada recentemente ao curso e é um rascunho inicial que ainda pode estar aguardando revisão. 4 | 5 | Até agora, usamos o Tor com os nossos serviços Bitcoin, mas também podemos usá-lo para proteger outros serviços em nossa máquina, melhorando a segurança e a privacidade. Esta seção demonstra como fazer isso, introduzindo um serviço ```ssh``` oculto para fazer o login remotamente usando o Tor. 6 | 7 | ## Criando Serviços SSH Ocultos 8 | 9 | Novos serviços são criados adicionando-os ao arquivo ```/etc/tor/torrc```: 10 | ``` 11 | $ su 12 | # cat >> /etc/tor/torrc << EOF 13 | HiddenServiceDir /var/lib/tor/hidden-service-ssh/ 14 | HiddenServicePort 22 127.0.0.1:22 15 | EOF 16 | # exit 17 | ``` 18 | Eis o que cada coisa significa: 19 | 20 | * HiddenServiceDir: Indica que temos um diretório de serviço oculto com a configuração necessária para este caminho. 21 | * HiddenServicePort: Indica a porta Tor a ser usada; no caso do SSH, geralmente é a 22. 22 | 23 | Depois de adicionar as linhas apropriadas ao nosso arquivo ```torrc```, precisaremos reiniciar o Tor: 24 | ``` 25 | $ sudo /etc/init.d/tor restart 26 | ``` 27 | 28 | Após a reinicialização, nosso ```HiddenServiceDir``` deve ter novos arquivos da seguinte forma: 29 | ``` 30 | $ sudo ls -l /var/lib/tor/hidden-service-ssh 31 | total 16 32 | drwx--S--- 2 debian-tor debian-tor 4096 Jul 22 14:55 authorized_clients 33 | -rw------- 1 debian-tor debian-tor 63 Jul 22 14:56 hostname 34 | -rw------- 1 debian-tor debian-tor 64 Jul 22 14:55 hs_ed25519_public_key 35 | -rw------- 1 debian-tor debian-tor 96 Jul 22 14:55 hs_ed25519_secret_key 36 | ``` 37 | O arquivo ```hostname``` neste diretório contém nosso novo ID onion: 38 | ``` 39 | $ sudo cat /var/lib/tor/hidden-service-ssh/hostname 40 | qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion 41 | ``` 42 | Podemos nos conectar ao serviço oculto ```ssh``` usando o ```torify``` e esse endereço: 43 | ``` 44 | $ torify ssh standup@qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion 45 | The authenticity of host 'qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion (127.42.42.0)' can't be established. 46 | ECDSA key fingerprint is SHA256:LQiWMtM8qD4Nv7eYT1XwBPDq8fztQafEJ5nfpNdDtCU. 47 | Are you sure you want to continue connecting (yes/no)? yes 48 | Warning: Permanently added 'qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion' (ECDSA) to the list of known hosts. 49 | standup@qwkemc3vusd73glx22t3sglf7izs75hqodxsgjqgqlujemv73j73qpid.onion's password: 50 | ``` 51 | ## Resumo: Adicionando Serviços SSH Ocultos 52 | 53 | Agora que instalamos o Tor e sabemos como usá-lo, podemos adicionar outros serviços ao Tor. Apenas adicionamos as linhas ao nosso ```torrc``` (no nosso servidor) e o conectamos com o ```torify``` (no nosso cliente). 54 | 55 | > :fire: ***Qual é o poder de utilizar outros serviços ocultos?*** Cada vez que acessamos um serviço em nosso servidor remotamente, deixamos pegadas na rede. Mesmo que os dados sejam criptografados usando SSH (ou TLS), os vigias da rede podem ver de onde estamos nos conectando, para onde estamos conectando e qual serviço estamos usando. Isso realmente importa pra nós? Esta é a pergunta que devemos fazer. Mas se a resposta for "Sim", podemos proteger a conexão com um serviço oculto. 56 | 57 | ## O Que Vem Depois? 58 | 59 | Para um tipo diferente de privacidade, vamos seguir para "Usando o I2P" com o [Capítulo Quize: Usando o I2P](15_0_Using_i2p.md) -------------------------------------------------------------------------------- /pt/15_0_Using_i2p.md: -------------------------------------------------------------------------------- 1 | # Capítulo 15: Usando o I2P 2 | 3 | Existem alternativas ao Tor. Uma é o Projeto Internet Invisível (I2P, ou Invisible Internet Project em inglês), uma camada de rede privada e totalmente criptografada. Ele utiliza um [banco de dados de rede](https://geti2p.net/pt-br/docs/how/network-database) distribuído e túneis criptografados unidirecionais entre os usuários. A maior diferença do I2P para o Tor é que o segundo é, em essência, uma rede de proxy que oferece serviços de internet de uma forma privada, enquanto que o I2P é fundamentalmente uma rede separada que oferece serviços I2P apenas à rede I2P, criando uma "rede dentro de uma rede". No entanto, podemos querer tê-la apenas como uma alternativa, para que não dependamos apenas do Tor. 4 | 5 | No momento, o I2P não está instalada com o [Bitcoin Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts) porque o suporte ao I2P foi adicionado recentemente ao Bitcoin Core. No entanto, neste capítulo, iremos explicar como podemos instalá-lo manualmente. 6 | 7 | ## Objetivos para Este Capítulo 8 | 9 | Depois de trabalharmos neste capítulo, um desenvolvedor será capaz de: 10 | 11 | - Executar o Bitcoin Core como um serviço I2P. 12 | 13 | Objetivos secundários incluem a habilidade de: 14 | 15 | - Compreender a rede I2P; 16 | - Aprender a diferença entre o Tor e o I2P. 17 | 18 | ## Tabela de Conteúdo 19 | 20 | * [Seção Um: Bitcoin Core como um Serviço I2P (Projeto Internet Invisível)](15_1_i2p_service.md) -------------------------------------------------------------------------------- /pt/16_0_Talking_to_Bitcoind.md: -------------------------------------------------------------------------------- 1 | # Capítulo 16: Conversando com Bitcoind com C 2 | 3 | Enquanto trabalhamos com Bitcoin Scripts, atingimos os limites do que era possível com o `bitcoin-cli`: Atualmente, ele não pode ser usado para gerar transações contendo scripts incomuns. Os scripts shell também não são bons para algumas coisas, como criar programas de escuta que estão constantemente em polling. Felizmente, existem outras maneiras de acessar a rede Bitcoin: Através de APIs programáveis. 4 | 5 | Esta seção se concentra em três diferentes bibliotecas que podem ser usadas como base de programação C sofisticada: Uma biblioteca RPC e uma biblioteca JSON que juntas permitem recriar muito do que fazemos nos scripts de shell, porém, usando C; enquanto uma biblioteca ZMQ nos conecta a notificações, algo que não conseguiríamos acessar até agora. (O próximo capítulo cobrirá uma biblioteca ainda mais sofisticada chamada Libwally, para finalizar esta introdução à programação do Bitcoin com C). 6 | 7 | ## Objetivos deste capítulo 8 | 9 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 10 | 11 | * Criar programas C que usam RPC para conversar com o Bitcoind; 12 | * Criar programas C que usam ZMQ para conversar com o Bitcoind. 13 | 14 | Os objetivos secundários do capítulo incluem a capacidade de: 15 | 16 | * Entender como usar uma biblioteca RPC; 17 | * Entender como usar uma biblioteca JSON; 18 | * Compreender as capacidades do ZMQ; 19 | * Entender como usar uma biblioteca ZMQ. 20 | 21 | ## Tabela de Conteúdo 22 | 23 | * [Seção 1: Acessando o Bitcoind em C com Bibliotecas RPC](16_1_Accessing_Bitcoind_with_C.md) 24 | * [Seção 2: Programando o Bitcoind em C com Bibliotecas RPC](16_2_Programming_Bitcoind_with_C.md) 25 | * [Seção 3: Recebendo Notificações em C com Bibliotecas ZMQ](16_3_Receiving_Bitcoind_Notifications_with_C.md) 26 | -------------------------------------------------------------------------------- /pt/17_0_Programming_with_Libwally.md: -------------------------------------------------------------------------------- 1 | # Capítulo 17: Programando com Libwally 2 | 3 | O capítulo anterior apresentou três bibliotecas C, para RPC, JSON e ZMQ, todas destinadas a interagir diretamente com o `bitcoind`, assim como você vem fazendo desde o início. Mas às vezes você pode querer codificar sem acesso direto a um `bitcoind`. Isso pode ser devido a um cliente offline ou apenas porque você deseja manter algumas funcionalidades internas de seu programa C. Você também pode querer se aprofundar na funcionalidade da carteira, como criação de palavras mnemônicas ou derivação de endereços. É aí que entra Libwally: é uma biblioteca de carteira para C, C ++, Java, NodeJS ou Python, com wrappers também disponíveis para outras linguagens, como Swift. 4 | 5 | Este capítulo aborda a funcionalidade possível dentro do Libwally, a maioria das quais complementa o trabalho que você fez através do acesso RPC ao `bitcoind`, mas algumas das quais o replicam. Ele também mostra como integrar esse trabalho com os clientes RPC com os quais você está mais familiarizado. No entanto, observe que esta é apenas uma introdução básica ao Libwally. Vários de seus conjuntos de funções mais importantes são destacados, mas nunca fazemos mais do que apresentar uma introdução. Se você acha suas funções úteis ou intrigantes, então você precisará se aprofundar muito mais do que este curso pode cobrir. 6 | 7 | ## Objetivos Deste Capítulo 8 | 9 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 10 | 11 | * Usar as funções de carteira com o Libwally; 12 | * Realizar manipulações de PSBTs e transações com o Libwally; 13 | * Implementar designs que combinem o Libwally e o RPC. 14 | 15 | Os objetivos secundários do capítulo incluem a capacidade de: 16 | 17 | * Compreender palavras mnemônicas BIP39; 18 | * Conhecer mais sobre as carteiras hierárquicas BIP32; 19 | * Sintetizar a profundidade funcional do Libwally. 20 | 21 | ## Tabela de Conteúdo 22 | 23 | * [Seção 1: Configurando a Libwally](17_1_Setting_Up_Libwally.md) 24 | * [Seção 2: Usando BIP39 na Libwally](17_2_Using_BIP39_in_Libwally.md) 25 | * [Seção 3: Usando BIP32 na Libwally](17_3_Using_BIP32_in_Libwally.md) 26 | * [Seção 4: Usando PSBTs na Libwally](17_4_Using_PSBTs_in_Libwally.md) 27 | * [Seção 5: Usando Scripts na Libwally](17_5_Using_Scripts_in_Libwally.md) 28 | * [Seção 6: Usando Outras Funções na Libwally](17_6_Using_Other_Functions_in_Libwally.md) 29 | * [Seção 7: Integrando Libwally e Bitcoin-CLI](17_7_Integrating_Libwally_and_Bitcoin-CLI.md) -------------------------------------------------------------------------------- /pt/18_0_Talking_to_Bitcoind_Other.md: -------------------------------------------------------------------------------- 1 | # Capítulo 18: Conversando com o Bitcoind com Outras Linguagens 2 | 3 | Agora devemos ter uma base sólida para trabalhar com Bitcoin usando a linguagem C, não apenas usando as bibliotecas RPC, JSON e ZMQ para interagir diretamente com o `bitcoind`, mas também, utilizando as bibliotecas Libwally para complementar esse trabalho. O C é uma ótima linguagem para prototipagem e abstração, porém provavelmente não é o que estamos usando para programar. Este capítulo, portanto, faz uma apresentação rápida de seis outras linguagens de programação, demonstrando a funcionalidade mais básica do Bitcoin em cada uma, permitindo que possamos expandir as lições da linha de comando e do C para a linguagem de programação que desejarmos. 4 | 5 | Cada uma das seções contém aproximadamente as mesmas informações, o foco será: criar uma conexão RPC, examinar a carteira, criar um novo endereço e criar uma transação. No entanto, há alguma mudança entre as linguagens, mostrando diferentes aspectos dos comandos RPC do Bitcoin em diferentes exemplos. Em particular, algumas linguagens usam a metodologia fácil do `sendtoaddress`, enquanto outras usam uma metodologia mais difícil para a criação de uma transação bruta do zero. 6 | 7 | ## Objetivos Deste Capítulo 8 | 9 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 10 | 11 | * Preparar ambientes de desenvolvimento para o Bitcoin para uma variedade de linguagens; 12 | * Usar as funções de carteira em várias linguagens; 13 | * Usar funções de transação em uma variedade de linguagens. 14 | 15 | Os objetivos secundários do capítulo incluem a capacidade de: 16 | 17 | * Saber mais sobre o Bitcoin RPC por meio de interações com uma variedade de linguagens. 18 | 19 | ## Tabela de Conteúdo 20 | 21 | * [Seção 1: Acessando o Bitcoind com Go](18_1_Accessing_Bitcoind_with_Go.md) 22 | * [Seção 2: Acessando o Bitcoind com Java](18_2_Accessing_Bitcoind_with_Java.md) 23 | * [Seção 3: Acessando o Bitcoind com NodeJS](18_3_Accessing_Bitcoind_with_NodeJS.md) 24 | * [Seção 4: Acessando o Bitcoind com Python](18_4_Accessing_Bitcoind_with_Python.md) 25 | * [Seção 5: Acessando o Bitcoind com Rust](18_5_Accessing_Bitcoind_with_Rust.md) 26 | * [Seção 6: Acessando o Bitcoind com Swift](18_6_Accessing_Bitcoind_with_Swift.md) -------------------------------------------------------------------------------- /pt/19_0_Understanding_Your_Lightning_Setup.md: -------------------------------------------------------------------------------- 1 | # Capítulo 19: Compreendendo Nossa Configuração da Lightning 2 | 3 | > :information_source: **NOTA:** Este é um rascunho que está em andamento. Seu objetivo é que possa obter alguns comentários dos revisores iniciais. Ainda não está pronto para ser produzido. 4 | 5 | O capítulo anterior concluiu nosso trabalho com o Bitcoin propriamente dito, por meio do CLI, scripts e linguagens de programação. No entanto, existem muitos outros utilitários dentro do ecossistema Bitcoin. Neste capítulo e no próximo, iremos cobrir o que pode ser o maior e mais importante deles, a Lightning Network. Aqui, começaremos a trabalhar com a interface de linha de comando `lightning-cli`, entendendo a configuração do c-lightning e dos seus recursos, incluindo alguns exemplos e configuração básica. 6 | 7 | ## Objetivos Deste Capítulo 8 | 9 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 10 | 11 | * Avaliar se um node c-lightning está instalado e atualizado; 12 | * Executar comandos básicos de uma carteira Lightning; 13 | * Criar um canal na Lightning. 14 | 15 | Os objetivos secundários do capítulo incluem a capacidade de: 16 | 17 | * Compreender a configuração básica da Lightning; 18 | * Compreender a interação dos canais Lightning; 19 | * Entender como usar a Lightning. 20 | 21 | ## Tabela de Conteúdo 22 | 23 | * [Seção 1: Verificando Nossa Configuração da c-lightning](19_1_Verifying_Your_Lightning_Setup.md) 24 | * [Seção 2: Conhecendo Nossa Configuração da c-lightning](19_2_Knowing_Your_lightning_Setup.md) 25 | * [Adendo: Acessando um Segundo Node Lightning](19_2__Interlude_Accessing_a_Second_Lightning_Node.md) 26 | * [Seção 3: Criando um Canal Lightning](19_3_Setting_Up_a_Channel.md) -------------------------------------------------------------------------------- /pt/20_0_Using_Lightning.md: -------------------------------------------------------------------------------- 1 | # Capítulo 20: Usando a Lightning 2 | 3 | > :information_source: **NOTA:** Este é um rascunho que está em andamento, para que possa obter alguns comentários dos revisores iniciais. Ainda não está pronto. 4 | 5 | Neste capítulo, continuaremos trabalhando com a interface de linha de comando `lightning-cli`. Criaremos invoices, realizaremos pagamentos e fecharemos canais, todas as principais atividades para se usar a Lightning. 6 | 7 | ## Objetivos Deste Capítulo 8 | 9 | Depois de trabalhar neste capítulo, um desenvolvedor será capaz de: 10 | 11 | * Efetuar pagamentos na Lightning Network; 12 | * Aplicar o fechamento de um canal Lightning. 13 | 14 | Os objetivos secundários do capítulo incluem a capacidade de: 15 | 16 | * Compreender o formato dos invoices; 17 | * Entender o ciclo de vida dos pagamentos da Lightning Network; 18 | * Saber como expandir a Lightning Network. 19 | 20 | ## Tabela de Conteúdo 21 | 22 | * [Seção 1: Gerando um Invoice](20_1_Generate_a_Payment_Request.md) 23 | * [Seção 2: Pagando um Invoice](20_2_Paying_a_Invoice.md) 24 | * [Seção 3: Fechando um Canal Lightning](20_3_Closing_a_Channel.md) 25 | * [Seção 4: Expandindo a Lightning Network](20_4_Lightning_Network_Review.md) 26 | -------------------------------------------------------------------------------- /pt/A0_Appendices.md: -------------------------------------------------------------------------------- 1 | # Apêndices 2 | 3 | O foco principal deste curso sugere uma configuração bastante padrão para os testes de Bitcoin. À seguir, vamos ver alguns apêndices que irão explicar melhor dessa configuração e algumas opções alternativas. 4 | 5 | ## Objetivos desta Seção 6 | 7 | Depois de trabalhar nestes apêndices, um desenvolvedor será capaz de: 8 | 9 | * Decidir entre vários métodos de como criar uma blockchain do Bitcoin. 10 | 11 | Os objetivos secundários do apêndice incluem a capacidade de: 12 | 13 | * Compreender a configuração do Bitcoin Standup; 14 | * Fazer uma compilação de Bitcoin à mão; 15 | * Compreender o poder do Regtest; 16 | * Use um ambiente Regtest. 17 | 18 | ## Tabela de Conteúdo 19 | 20 | * [Apêndice 1: Compreendendo o Bitcoin Standup](A1_0_Understanding_Bitcoin_Standup.md) 21 | * [Apêndice 2: Compilando Bitcoin da Fonte](A2_0_Compiling_Bitcoin_from_Source.md) 22 | * [Apêndice 3: Usando o Regtest do Bitcoin](A3_0_Using_Bitcoin_Regtest.md) -------------------------------------------------------------------------------- /pt/A1_0_Understanding_Bitcoin_Standup.md: -------------------------------------------------------------------------------- 1 | # Apêndice 1: Compreendendo o Bitcoin Standup 2 | 3 | Na seção [§2.1: Configurando um Bitcoin Core VPS com StackScript](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md) explicamos o processo de criação de um node de Bitcoin usando [Bitcoin-Standup-Scripts](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts). O apêndice à seguir explica o que as principais seções do script fazem. Podemos acompanhar em [Linode Standup](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts/blob/master/Scripts/LinodeStandUp.sh) em outra janela. 4 | 5 | ## Etapa 1: Nome do Host 6 | 7 | O nome do seu host é armazenado em `/etc/hostname` e definido com o comando `hostname`. Ele também aparece em `/etc/hosts`. 8 | 9 | ## Etapa 2: Fuso Horário 10 | 11 | O fuso horário do nosso host é armazenado em `/etc/timezone`, então um arquivo apropriado do `/usr/share/zoneinfo/` é copiado para o `/etc/localtime`. 12 | 13 | ## Etapa 3: Atualizando o Debian 14 | 15 | O gerenciador de pacotes `apt-get` é usado para deixar nossa máquina atualizada e instalar o `gnupg`, o gerador de números aleatórios `haveged`, e o firewall simples `ufw`. 16 | 17 | Nossa máquina está configurada para se manter automaticamente atualizada com o `echo "unattended-upgrades unattended-upgrades / enable_auto_updates boolean true "| debconf-set-selections`. 18 | 19 | ## Etapa 4: Configurando um Usuário 20 | 21 | Um usuário `standup` é criado, o qual será usado para nossas aplicações do Bitcoin. Ele também tem permissões `sudo`, permitindo que executemos ações privilegiadas com este usuário. 22 | 23 | Se fornecemos uma chave SSH, ela permitirá o acesso a esta conta (caso contrário, devemos usar a senha criada na configuração). 24 | 25 | Se fornecemos um endereço IP, o acesso `ssh` será limitado a esse endereço, de acordo com `/etc/hosts.allow`. 26 | 27 | ## Etapa 5: Configurando o Tor 28 | 29 | O Tor é instalado para fornecer serviços protegidos (ocultos) para acessar os comandos RPC do Bitcoin através do nosso servidor. Podemos consultar a seção [§14.1: Verificando Nossa Configuração do Tor](14_1_Verifying_Your_Tor_Setup.md) para obter mais informações sobre a configuração do Tor. 30 | 31 | Se criarmos um cliente autorizado para os serviços ocultos, o acesso será limitado a essa chave, que está em `/var/lib/tor/standup/authorized_clients`. Caso contrário, na seção [§14.2](14_2_Changing_Your_Bitcoin_Hidden_Services.md) explicamos como podemos fazê-la depois. 32 | 33 | ## Etapa 6: Instalando o Bitcoin 34 | 35 | Bitcoin é instalado no `~standup/.bitcoin`. Nossa configuração é armazenada no `~standup/.bitcoin/bitcoin.conf`. 36 | 37 | Precisamos nos certificar de que as somas de verificação (checksum) foram analisadas de acordo com a seção [§2.1](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md), caso contrário, podemos estar expostos a um ataque de cadeia de produção. 38 | 39 | ## Etapa 7: Instalando o Codificador QR 40 | 41 | Para manter tudo compatível com [GordianSystem](https://github.com/BlockchainCommons/GordianSystem), um código QR é criado e está em `/qrcode.png`. Isso pode ser lido em um cliente QuickConnect como [GordianWallet](https://github.com/BlockchainCommons/GordianWallet-iOS). 42 | 43 | ## Conclusão - Compreendendo o Bitcoin Standup 44 | 45 | O Bitcoin Standup usa scripts para tentar combinar muitas das funcionalidades de um [GordianNode](https://github.com/BlockchainCommons/GordianNode-macOS). Ele deve fornecer a nós um ambiente Bitcoin seguro construído em uma base de Bitcoin Core com Tor para nos comunicarmos com o RPC. 46 | 47 | ## O Que Vem Depois? 48 | 49 | Se estivermos no processo de criação de um node Bitcoin para o uso neste curso, devemos voltar para a seção [§2.1](02_1_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md). 50 | 51 | Se estivermos lendo os apêndices, podemos continuar no [Apêndice 2: Compilando Bitcoin da Fonte](A2_0_Compiling_Bitcoin_from_Source.md). -------------------------------------------------------------------------------- /public/LBftCLI-compiling_bitcoin-db4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/public/LBftCLI-compiling_bitcoin-db4.png -------------------------------------------------------------------------------- /public/LBftCLI-compiling_bitcoin-git.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlockchainCommons/Learning-Bitcoin-from-the-Command-Line/bba348c9441e712f3b899c32ef5f6d3596159ada/public/LBftCLI-compiling_bitcoin-git.png -------------------------------------------------------------------------------- /src/04_2_i_txfee-calc.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -z $1 ]; 4 | then 5 | echo "You must include the raw transaction hex as an argument."; 6 | exit; 7 | fi 8 | 9 | usedtxid=($(bitcoin-cli decoderawtransaction $1 | jq -r '.vin | .[] | .txid')) 10 | usedvout=($(bitcoin-cli decoderawtransaction $1 | jq -r '.vin | .[] | .vout')) 11 | btcin=$(for ((i=0; i<${#usedtxid[*]}; i++)); do txid=${usedtxid[i]}; vout=${usedvout[i]}; bitcoin-cli listunspent | jq -r '.[] | select (.txid | contains("'${txid}'")) | select(.vout | contains('$vout')) | .amount'; done | awk '{s+=$1} END {print s}') 12 | btcout=$(bitcoin-cli decoderawtransaction $1 | jq -r '.vout [] | .value' | awk '{s+=$1} END {print s}') 13 | btcout_f=$(awk -v btcout="$btcout" 'BEGIN { printf("%f\n", btcout) }' "2147483647" )) || (( $1 < "-2147483647" )); 10 | then 11 | echo "Your number ($1) must be between -2147483647 and 2147483647"; 12 | exit; 13 | fi 14 | 15 | if [ $1 -lt 0 ]; 16 | then 17 | integer=$(echo $((-$1))); 18 | negative=1; 19 | else 20 | integer=$1; 21 | negative=0; 22 | fi 23 | 24 | hex=$(printf '%08x\n' $integer | sed 's/^\(00\)*//'); 25 | 26 | hexfirst=$(echo $hex | cut -c1) 27 | [[ 0x$hexfirst -gt 0x7 ]] && hex="00"$hex 28 | 29 | lehex=$(echo $hex | tac -rs .. | echo "$(tr -d '\n')"); 30 | 31 | if [ "$negative" -eq "1" ]; 32 | then 33 | lehex=$(printf '%x\n' $((0x$lehex | 0x80))) 34 | fi 35 | 36 | size=$(echo -n $lehex | wc -c | awk '{print $1/2}'); 37 | hexcodeprefix=$(printf '%02x\n' $size); 38 | 39 | echo "Integer: $1"; 40 | echo "LE Hex: $lehex"; 41 | echo "Length: $size bytes"; 42 | echo "Hexcode: $hexcodeprefix$lehex"; 43 | -------------------------------------------------------------------------------- /src/16_1_getmininginfo.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | 6 | bitcoinrpc_cl_t *rpc_client; 7 | bitcoinrpc_method_t *getmininginfo = NULL; 8 | bitcoinrpc_resp_t *btcresponse = NULL; 9 | bitcoinrpc_err_t btcerror; 10 | 11 | json_t *jsonresponse = NULL; 12 | json_t *jsonresult = NULL; 13 | json_t *jsonblocks = NULL; 14 | int blocks; 15 | 16 | bitcoinrpc_global_init(); 17 | 18 | rpc_client = bitcoinrpc_cl_init_params ("StandUp", "YOUR-RPC-PASSWD", "127.0.0.1", 18332); 19 | 20 | if (rpc_client) { 21 | getmininginfo = bitcoinrpc_method_init(BITCOINRPC_METHOD_GETMININGINFO); 22 | 23 | if (!getmininginfo) { 24 | 25 | printf("ERROR: Unable to initialize getmininginfo method!\n"); 26 | exit(-1); 27 | 28 | } 29 | 30 | btcresponse = bitcoinrpc_resp_init(); 31 | if (!btcresponse) { 32 | 33 | printf("Error: Cannot initialize response object!\n"); 34 | exit(-1); 35 | 36 | } 37 | 38 | bitcoinrpc_call(rpc_client, getmininginfo, btcresponse, &btcerror); 39 | 40 | if (btcerror.code != BITCOINRPCE_OK) { 41 | 42 | 43 | printf("Error: getmininginfo error code %d [%s]\n", btcerror.code,btcerror.msg); 44 | exit(-1); 45 | 46 | } 47 | 48 | printf("Full Response: "); 49 | jsonresponse = bitcoinrpc_resp_get (btcresponse); 50 | printf ("%s\n", json_dumps (jsonresponse, JSON_INDENT(2))); 51 | 52 | printf("\nJust the Result: "); 53 | jsonresult = json_object_get(jsonresponse,"result"); 54 | printf ("%s\n", json_dumps (jsonresult, JSON_INDENT(2))); 55 | 56 | jsonblocks = json_object_get(jsonresult,"blocks"); 57 | blocks = json_integer_value(jsonblocks); 58 | printf("\nBlock Count: %d\n",blocks); 59 | 60 | json_decref(jsonblocks); 61 | json_decref(jsonresult); 62 | json_decref(jsonresponse); 63 | 64 | } else { 65 | 66 | printf("ERROR: Failed to connect to server!\n"); 67 | 68 | } 69 | 70 | bitcoinrpc_cl_free(rpc_client); 71 | bitcoinrpc_global_cleanup(); 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/16_1_testbitcoin.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | 6 | bitcoinrpc_global_init(); 7 | 8 | bitcoinrpc_cl_t *rpc_client; 9 | rpc_client = bitcoinrpc_cl_init_params ("StandUp", "YOUR-RPC-PASSWD", "127.0.0.1", 18332); 10 | 11 | if (rpc_client) { 12 | 13 | printf("Successfully connected to server!\n"); 14 | 15 | } else { 16 | 17 | printf("Failed to connect to server!\n"); 18 | 19 | } 20 | 21 | bitcoinrpc_global_cleanup(); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/16_3_chainlistener.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(int argc, char ** argv) { 3 | 4 | char *zmqserver; 5 | char *topic; 6 | 7 | if (argc < 3) { 8 | printf("\nUSAGE:\nchainlistener \n\n"); 9 | return 0; 10 | } else { 11 | zmqserver = argv[1]; 12 | topic = argv[2]; 13 | } 14 | 15 | zsock_t *socket = zsock_new_sub(zmqserver, topic); 16 | assert(socket); 17 | 18 | while(1) { 19 | zmsg_t *msg; 20 | int rc = zsock_recv(socket, "m", &msg); 21 | assert(rc == 0); 22 | 23 | char *header = zmsg_popstr(msg); 24 | zframe_t *zdata = zmsg_pop(msg); 25 | unsigned int *no = (unsigned int*)zmsg_popstr(msg); 26 | 27 | char *data = zframe_strhex(zdata); 28 | int len = zframe_size(zdata); 29 | printf("Size: %d\n", len); 30 | printf("Data: %s", data); 31 | printf("\nNo: %d\n", *no); 32 | 33 | free(header); 34 | free(data); 35 | free(no); 36 | free(zdata); 37 | zmsg_destroy(&msg); 38 | sleep(1); 39 | } 40 | zsock_destroy(&socket); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /src/17_1_testwally.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "wally_core.h" 3 | 4 | int main(void) { 5 | 6 | int lw_response; 7 | 8 | lw_response = wally_init(0); 9 | printf("Startup: %d\n",lw_response); 10 | 11 | wally_cleanup(0); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/17_2_genmnemonic.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "sodium.h" 3 | #include "wally_core.h" 4 | #include "wally_bip39.h" 5 | 6 | int main(void) { 7 | 8 | int lw_response; 9 | 10 | /* 1. Initialize Libwally */ 11 | 12 | lw_response = wally_init(0); 13 | 14 | if (lw_response) { 15 | 16 | printf("Error: Wally_init failed: %d\n",lw_response); 17 | exit(-1); 18 | 19 | } 20 | 21 | /* 2. Generate Entropy */ 22 | 23 | unsigned char entropy[16]; 24 | randombytes_buf(entropy, 16); 25 | 26 | /* 3. Translate into Mnemonic */ 27 | 28 | char *mnem = NULL; 29 | lw_response = bip39_mnemonic_from_bytes(NULL,entropy,16,&mnem); 30 | 31 | if (lw_response) { 32 | 33 | printf("Error: bip39_mnemonic_from_bytes failed: %d\n",lw_response); 34 | exit(-1); 35 | 36 | } 37 | 38 | printf("Mnemonic: %s\n",mnem); 39 | 40 | /* 4. Validate a Mnemonic */ 41 | 42 | lw_response = bip39_mnemonic_validate(NULL,mnem); 43 | 44 | if (lw_response) { 45 | 46 | printf("Error: Mnemonic did not validate: %d\n",lw_response); 47 | exit(-1); 48 | 49 | } else { 50 | 51 | printf("Mnemonic validated!\n"); 52 | 53 | } 54 | 55 | /* 5. Translate into Seed */ 56 | 57 | unsigned char seed[BIP39_SEED_LEN_512]; 58 | size_t seed_len; 59 | 60 | lw_response = bip39_mnemonic_to_seed(mnem,NULL,seed,BIP39_SEED_LEN_512,&seed_len); 61 | 62 | if (lw_response) { 63 | 64 | printf("Error: bip39_mnemonic_to_seed failed: %d\n",lw_response); 65 | exit(-1); 66 | 67 | } 68 | 69 | /* 6. Print the Seed */ 70 | 71 | char *seed_hex; 72 | wally_hex_from_bytes(seed,sizeof(seed),&seed_hex); 73 | printf("Seed: %s\n",seed_hex); 74 | 75 | /* Always cleanup: the docs clearly tell us what to free */ 76 | 77 | wally_free_string(mnem); 78 | wally_free_string(seed_hex); 79 | wally_cleanup(0); 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/17_4_createemptypsbt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "wally_core.h" 4 | #include "wally_psbt.h" 5 | #include "wally_transaction.h" 6 | 7 | int main(void) { 8 | 9 | int lw_response; 10 | struct wally_psbt *psbt; 11 | 12 | char *psbt_64; 13 | 14 | lw_response = wally_psbt_init_alloc(0,1,1,0,&psbt); 15 | 16 | if (lw_response) { 17 | 18 | printf("Error: Wally_psbt_init_alloc failed: %d\n",lw_response); 19 | exit(-1); 20 | 21 | } 22 | 23 | struct wally_tx *gtx; 24 | lw_response = wally_tx_init_alloc(0,0,1,1,>x); 25 | 26 | if (lw_response) { 27 | 28 | printf("Error: Wally_tx_init_alloc failed: %d\n",lw_response); 29 | exit(-1); 30 | 31 | } 32 | 33 | lw_response = wally_psbt_set_global_tx(psbt,gtx); 34 | 35 | if (lw_response) { 36 | 37 | printf("Error: Wally_psbt_set_global_tx failed: %d\n",lw_response); 38 | exit(-1); 39 | 40 | } 41 | 42 | wally_psbt_to_base64(psbt,0,&psbt_64); 43 | printf("%s\n",psbt_64); 44 | 45 | wally_tx_free(gtx); 46 | wally_psbt_free(psbt); 47 | 48 | wally_cleanup(0); 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/17_4_examinepsbt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "wally_core.h" 3 | #include "wally_psbt.h" 4 | 5 | int main(int argc, char *argv[]) { 6 | 7 | /* 1. Request a PSBT */ 8 | 9 | if (argc != 2) { 10 | 11 | printf("ERROR: Only %i arguments! Correct usage is '%s [psbt]'\n",argc-1,argv[0]); 12 | exit(-1); 13 | 14 | } 15 | char *psbt_64 = argv[1]; 16 | 17 | /* 2. Convert the PSBT */ 18 | 19 | int lw_response; 20 | 21 | struct wally_psbt *psbt; 22 | 23 | lw_response = wally_psbt_from_base64(psbt_64,&psbt); 24 | 25 | if (lw_response) { 26 | 27 | printf("Error: Wally_psbt_from_base64 failed: %d\n",lw_response); 28 | exit(-1); 29 | 30 | } 31 | 32 | /* 3. Read the Inputs */ 33 | 34 | int inputs = psbt->num_inputs; 35 | printf("TOTAL INPUTS: %i\n",inputs); 36 | 37 | /* This will crash if the inputs are not filled in, or if there are non_witness_utxos */ 38 | 39 | for (int i = 0 ; i < inputs ; i++) { 40 | printf("\nINPUT #%i: %i satoshis\n",i, psbt->inputs[i].witness_utxo->satoshi); 41 | 42 | char *script_hex; 43 | wally_hex_from_bytes(psbt->inputs[i].witness_utxo->script,psbt->inputs[i].witness_utxo->script_len,&script_hex); 44 | printf("scriptPubKey: %s\n",script_hex); 45 | wally_free_string(script_hex); 46 | 47 | } 48 | 49 | /* 4. Read the Outputs */ 50 | 51 | int outputs = psbt->num_outputs; 52 | printf("\nTOTAL OUTPUTS: %i\n",outputs); 53 | 54 | /* This will crash if the outputs are not filled in */ 55 | 56 | for (int i = 0 ; i < outputs ; i++) { 57 | 58 | char *pubkey_hex; 59 | wally_hex_from_bytes(psbt->tx->outputs[i].script,psbt->tx->outputs[i].script_len,&pubkey_hex); 60 | printf("\nINPUT #%i\n",i); 61 | printf("scriptPubKey: %s\n",pubkey_hex); 62 | wally_free_string(pubkey_hex); 63 | } 64 | 65 | wally_cleanup(0); 66 | } 67 | -------------------------------------------------------------------------------- /src/17_5_replacewithscript.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "wally_core.h" 5 | #include "wally_transaction.h" 6 | #include "wally_script.h" 7 | 8 | int main(int argc, char *argv[]) { 9 | 10 | if (argc != 3) { 11 | 12 | printf("ERROR: Only %i arguments! Correct usage is '%s [transaction hex] [serialized locking script]'\n",argc-1,argv[0]); 13 | exit(-1); 14 | 15 | } 16 | char *utxo_hex = argv[1]; 17 | char *script = argv[2]; 18 | 19 | int lw_response; 20 | size_t written; 21 | 22 | /* 1. Create the P2SH Script */ 23 | 24 | int script_length = strlen(script)/2; 25 | unsigned char bscript[script_length]; 26 | 27 | lw_response = wally_hex_to_bytes(script,bscript,script_length,&written); 28 | assert(lw_response == WALLY_OK); 29 | 30 | unsigned char p2sh[WALLY_SCRIPTPUBKEY_P2SH_LEN]; 31 | 32 | lw_response = wally_scriptpubkey_p2sh_from_bytes(bscript,sizeof(bscript),WALLY_SCRIPT_HASH160,p2sh,WALLY_SCRIPTPUBKEY_P2SH_LEN,&written); 33 | assert(lw_response == WALLY_OK); 34 | 35 | char *pubkey; 36 | lw_response = wally_hex_from_bytes(p2sh,sizeof(p2sh),&pubkey); 37 | 38 | /* 2. Create the Transaction */ 39 | 40 | struct wally_tx *tx; 41 | lw_response = wally_tx_init_alloc(2,0,1,1,&tx); 42 | assert(lw_response == WALLY_OK); 43 | 44 | /* 3. Create the Outputs with the P2SH */ 45 | 46 | struct wally_tx_output *tx_output; 47 | lw_response = wally_tx_output_init_alloc(95000,p2sh,sizeof(p2sh),&tx_output); 48 | assert(lw_response == WALLY_OK); 49 | 50 | lw_response = wally_tx_add_output(tx,tx_output); 51 | assert(lw_response == WALLY_OK); 52 | 53 | /* 4. Create the Inputs based on Hex */ 54 | 55 | struct wally_tx *utxo; 56 | lw_response = wally_tx_from_hex(utxo_hex,0,&utxo); 57 | assert(lw_response == WALLY_OK); 58 | 59 | struct wally_tx_input *tx_input; 60 | lw_response = wally_tx_input_init_alloc(utxo->inputs[0].txhash,sizeof(utxo->inputs[0].txhash),utxo->inputs[0].index,0,utxo->inputs[0].script,utxo->inputs[0].script_len,utxo->inputs[0].witness,&tx_input); 61 | assert(lw_response == WALLY_OK); 62 | lw_response = wally_tx_add_input(tx,tx_input); 63 | assert(lw_response == WALLY_OK); 64 | 65 | /* 5. Print It */ 66 | 67 | char *tx_hex; 68 | lw_response = wally_tx_to_hex(tx,0, &tx_hex); 69 | assert(lw_response == WALLY_OK); 70 | 71 | printf("%s\n",tx_hex); 72 | 73 | wally_free_string(tx_hex); 74 | wally_tx_free(tx); 75 | wally_tx_input_free(tx_input); 76 | wally_tx_output_free(tx_output); 77 | wally_tx_free(utxo); 78 | 79 | wally_cleanup(0); 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/18_1_blockinfo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "fmt" 6 | "github.com/btcsuite/btcd/rpcclient" 7 | ) 8 | 9 | func main() { 10 | connCfg := &rpcclient.ConnConfig{ 11 | Host: "localhost:18332", 12 | User: "StandUp", 13 | Pass: "6305f1b2dbb3bc5a16cd0f4aac7e1eba", 14 | HTTPPostMode: true, 15 | DisableTLS: true, 16 | } 17 | client, err := rpcclient.New(connCfg, nil) 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | defer client.Shutdown() 22 | 23 | blockCount, err := client.GetBlockCount() 24 | if err != nil { 25 | log.Fatal(err) 26 | } 27 | blockHash, err := client.GetBlockHash(blockCount) 28 | if err != nil { 29 | log.Fatal(err) 30 | } 31 | 32 | fmt.Printf("%d\n", blockCount) 33 | fmt.Printf("%s\n", blockHash.String()) 34 | } 35 | -------------------------------------------------------------------------------- /src/18_1_getaddress.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "fmt" 6 | "github.com/btcsuite/btcd/rpcclient" 7 | "github.com/btcsuite/btcd/chaincfg" 8 | ) 9 | 10 | func main() { 11 | connCfg := &rpcclient.ConnConfig{ 12 | Host: "localhost:18332", 13 | User: "StandUp", 14 | Pass: "431451790e3eee1913115b9dd2fbf0ac", 15 | HTTPPostMode: true, 16 | DisableTLS: true, 17 | Params: chaincfg.TestNet3Params.Name, 18 | } 19 | client, err := rpcclient.New(connCfg, nil) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | defer client.Shutdown() 24 | 25 | address, err := client.GetNewAddress("") 26 | if err != nil { 27 | log.Fatal(err) 28 | } 29 | fmt.Println(address) 30 | } 31 | -------------------------------------------------------------------------------- /src/18_1_getamountreceived.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "fmt" 6 | "github.com/btcsuite/btcd/rpcclient" 7 | "github.com/btcsuite/btcutil" 8 | "github.com/btcsuite/btcd/chaincfg" 9 | ) 10 | 11 | func main() { 12 | connCfg := &rpcclient.ConnConfig{ 13 | Host: "localhost:18332", 14 | User: "StandUp", 15 | Pass: "431451790e3eee1913115b9dd2fbf0ac", 16 | HTTPPostMode: true, 17 | DisableTLS: true, 18 | } 19 | client, err := rpcclient.New(connCfg, nil) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | defer client.Shutdown() 24 | 25 | defaultNet := &chaincfg.TestNet3Params 26 | addr, err := btcutil.DecodeAddress("mpGpCMX6SuUimDZKiVViuhd7EGyVxkNnha", defaultNet) 27 | if err != nil { 28 | log.Fatal(err) 29 | } 30 | wallet, err := client.GetReceivedByAddress(addr) 31 | if err != nil { 32 | log.Fatal(err) 33 | } 34 | 35 | fmt.Println(wallet) 36 | } 37 | -------------------------------------------------------------------------------- /src/18_1_getbalance.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "fmt" 6 | "github.com/btcsuite/btcd/rpcclient" 7 | ) 8 | 9 | func main() { 10 | connCfg := &rpcclient.ConnConfig{ 11 | Host: "localhost:18332", 12 | User: "StandUp", 13 | Pass: "431451790e3eee1913115b9dd2fbf0ac", 14 | HTTPPostMode: true, 15 | DisableTLS: true, 16 | } 17 | client, err := rpcclient.New(connCfg, nil) 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | defer client.Shutdown() 22 | 23 | wallet, err := client.GetBalance("*") 24 | if err != nil { 25 | log.Fatal(err) 26 | } 27 | 28 | fmt.Println(wallet) 29 | } 30 | -------------------------------------------------------------------------------- /src/18_1_lookuptransaction.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "fmt" 6 | "github.com/btcsuite/btcd/rpcclient" 7 | "github.com/btcsuite/btcd/chaincfg/chainhash" 8 | ) 9 | 10 | func main() { 11 | connCfg := &rpcclient.ConnConfig{ 12 | Host: "localhost:18332", 13 | User: "StandUp", 14 | Pass: "431451790e3eee1913115b9dd2fbf0ac", 15 | HTTPPostMode: true, 16 | DisableTLS: true, 17 | } 18 | client, err := rpcclient.New(connCfg, nil) 19 | if err != nil { 20 | log.Fatal(err) 21 | } 22 | defer client.Shutdown() 23 | 24 | chash, err := chainhash.NewHashFromStr("1661ce322c128e053b8ea8fcc22d17df680d2052983980e2281d692b9b4ab7df") 25 | if err != nil { 26 | log.Fatal(err) 27 | } 28 | transactions, err := client.GetTransaction(chash) 29 | if err != nil { 30 | log.Fatal(err) 31 | } 32 | 33 | fmt.Println(transactions) 34 | } 35 | -------------------------------------------------------------------------------- /src/18_1_sendtransaction.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "fmt" 6 | "github.com/btcsuite/btcd/rpcclient" 7 | "github.com/btcsuite/btcutil" 8 | "github.com/btcsuite/btcd/chaincfg" 9 | ) 10 | 11 | func main() { 12 | connCfg := &rpcclient.ConnConfig{ 13 | Host: "localhost:18332", 14 | User: "StandUp", 15 | Pass: "431451790e3eee1913115b9dd2fbf0ac", 16 | HTTPPostMode: true, 17 | DisableTLS: true, 18 | } 19 | client, err := rpcclient.New(connCfg, nil) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | defer client.Shutdown() 24 | 25 | defaultNet := &chaincfg.TestNet3Params 26 | addr, err := btcutil.DecodeAddress("n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi", defaultNet) 27 | if err != nil { 28 | log.Fatal(err) 29 | } 30 | sent, err := client.SendToAddress(addr, btcutil.Amount(1e4)) 31 | if err != nil { 32 | log.Fatal(err) 33 | } 34 | 35 | fmt.Println(sent) 36 | } 37 | -------------------------------------------------------------------------------- /src/18_2_App-getinfo.java: -------------------------------------------------------------------------------- 1 | package com.blockchaincommons.lbtc; 2 | 3 | import wf.bitcoin.javabitcoindrpcclient.BitcoinJSONRPCClient; 4 | import wf.bitcoin.javabitcoindrpcclient.BitcoindRpcClient; 5 | import wf.bitcoin.javabitcoindrpcclient.BitcoindRpcClient.MiningInfo; 6 | import wf.bitcoin.javabitcoindrpcclient.BitcoindRpcClient.AddressInfo; 7 | 8 | public class App 9 | { 10 | 11 | public static void main( String[] args ) throws Exception 12 | { 13 | 14 | BitcoindRpcClient rpcClient = new BitcoinJSONRPCClient("http://StandUp:6305f1b2dbb3bc5a16cd0f4aac7e1eba@localhost:18332"); 15 | 16 | MiningInfo info = rpcClient.getMiningInfo(); 17 | System.out.println("Mining Information"); 18 | System.out.println("------------------"); 19 | System.out.println("Chain......: " + info.chain()); 20 | System.out.println("Blocks.....: " + info.blocks()); 21 | System.out.println("Difficulty.: " + info.difficulty()); 22 | System.out.println("Hash Power.: " + info.networkHashps()); 23 | 24 | /* Replace this with an address from your system */ 25 | String addr1 = "mvLyH7Rs45c16FG2dfV7uuTKV6pL92kWxo"; 26 | 27 | AddressInfo addr1Info = rpcClient.getAddressInfo(addr1); 28 | System.out.println("Address: " + addr1Info.address()); 29 | System.out.println("MasterFingerPrint: " + addr1Info.hdMasterFingerprint()); 30 | System.out.println("HdKeyPath: " + addr1Info.hdKeyPath()); 31 | System.out.println("PubKey: " + addr1Info.pubKey()); 32 | 33 | System.out.println("Balance: " + rpcClient.getBalance()); 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/18_2_App-listen.java: -------------------------------------------------------------------------------- 1 | package com.blockchaincommons.lbtc; 2 | 3 | import wf.bitcoin.javabitcoindrpcclient.BitcoinAcceptor; 4 | import wf.bitcoin.javabitcoindrpcclient.BitcoinJSONRPCClient; 5 | import wf.bitcoin.javabitcoindrpcclient.BitcoinPaymentListener; 6 | import wf.bitcoin.javabitcoindrpcclient.BitcoindRpcClient; 7 | import wf.bitcoin.javabitcoindrpcclient.BitcoindRpcClient.*; 8 | 9 | public class App 10 | { 11 | 12 | public static void main( String[] args ) throws Exception 13 | { 14 | 15 | BitcoindRpcClient rpcClient = new BitcoinJSONRPCClient("http://StandUp:6 16 | 305f1b2dbb3bc5a16cd0f4aac7e1eba@localhost:18332"); 17 | 18 | String blockHash = rpcClient.getBestBlockHash(); 19 | 20 | BitcoinAcceptor acceptor = new BitcoinAcceptor(rpcClient, blockHash, 6, 21 | new BitcoinPaymentListener() { 22 | 23 | @Override 24 | public void transaction(Transaction tx) { 25 | System.out.println("Transaction: " + tx); 26 | } 27 | 28 | @Override 29 | public void block(String block) { 30 | System.out.println("Block: " + block); 31 | 32 | } 33 | }); 34 | acceptor.run(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/18_2_App-sendtx.java: -------------------------------------------------------------------------------- 1 | package com.blockchaincommons.lbtc; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.*; 5 | 6 | import wf.bitcoin.javabitcoindrpcclient.BitcoinJSONRPCClient; 7 | import wf.bitcoin.javabitcoindrpcclient.BitcoinRawTxBuilder; 8 | import wf.bitcoin.javabitcoindrpcclient.BitcoindRpcClient; 9 | import wf.bitcoin.javabitcoindrpcclient.BitcoindRpcClient.*; 10 | 11 | public class App 12 | { 13 | 14 | public static void main( String[] args ) throws Exception 15 | { 16 | 17 | BitcoindRpcClient rpcClient = new BitcoinJSONRPCClient("http://StandUp:6305f1b2dbb3bc5a16cd0f4aac7e1eba@localhost:18332"); 18 | 19 | /* 1. Prepare two address */ 20 | 21 | /* Use an address on your system with UTXOs */ 22 | String addr1 = "tb1qdqkc3430rexxlgnma6p7clly33s6jjgay5q8np"; 23 | System.out.println("Used address addr1: " + addr1); 24 | 25 | String addr2 = rpcClient.getNewAddress(); 26 | System.out.println("Created address addr2: " + addr2); 27 | 28 | /* 2. Find a UTXO */ 29 | 30 | List utxos = rpcClient.listUnspent(0, Integer.MAX_VALUE, addr1); 31 | System.out.println("Found " + utxos.size() + " UTXOs (unspent transaction outputs) belonging to addr1"); 32 | 33 | /* 3. Create a Transaction */ 34 | 35 | BitcoinRawTxBuilder txb = new BitcoinRawTxBuilder(rpcClient); 36 | 37 | /* 3.1 Fill the Input */ 38 | 39 | TxInput in = utxos.get(0); 40 | txb.in(in); 41 | 42 | /* 3.2 Fill the Output */ 43 | 44 | BigDecimal estimatedFee = BigDecimal.valueOf(0.00000200); 45 | BigDecimal txToAddr2Amount = utxos.get(0).amount().subtract(estimatedFee); 46 | txb.out(addr2, txToAddr2Amount); 47 | 48 | System.out.println("unsignedRawTx in amount: " + utxos.get(0).amount()); 49 | System.out.println("unsignedRawTx out amount: " + txToAddr2Amount); 50 | 51 | /* 4. Sign the Transaction */ 52 | 53 | String unsignedRawTxHex = txb.create(); 54 | System.out.println("Created unsignedRawTx from addr1 to addr2: " + unsignedRawTxHex); 55 | 56 | SignedRawTransaction srTx = rpcClient.signRawTransactionWithKey( 57 | unsignedRawTxHex, 58 | Arrays.asList(rpcClient.dumpPrivKey(addr1)), 59 | Arrays.asList(in), 60 | null); 61 | System.out.println("signedRawTx hex: " + srTx.hex()); 62 | System.out.println("signedRawTx complete: " + srTx.complete()); 63 | 64 | /* 5. Send the Transaction */ 65 | 66 | String sentRawTransactionID = rpcClient.sendRawTransaction(srTx.hex()); 67 | System.out.println("Sent signedRawTx (txID): " + sentRawTransactionID); 68 | 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/18_3_getinfo.js: -------------------------------------------------------------------------------- 1 | const RpcAgent = require('bcrpc'); 2 | agent = new RpcAgent({port: 18332, user: 'StandUp', pass: '6305f1b2dbb3bc5a16cd0 3 | f4aac7e1eba'}); 4 | 5 | agent.getBlockCount(function (err, blockCount) { 6 | if (err) 7 | throw Error(JSON.stringify(err)); 8 | console.log(blockCount.result); 9 | 10 | agent.getBlockHash(blockCount.result, function (err, hash) { 11 | if (err) 12 | throw Error(JSON.stringify(err)); 13 | console.log(hash.result); 14 | }); 15 | 16 | }); 17 | -------------------------------------------------------------------------------- /src/18_3_sendtx.js: -------------------------------------------------------------------------------- 1 | const RpcAgent = require('bcrpc'); 2 | agent = new RpcAgent({port: 18332, user: 'StandUp', pass: '6305f1b2dbb3bc5a16cd0 3 | f4aac7e1eba'}); 4 | 5 | agent.getNewAddress('-addresstype', 'legacy', function (err, newAddress) { 6 | if (err) 7 | throw Error(JSON.stringify(err)); 8 | console.log("Recipient: " + newAddress.result); 9 | 10 | agent.sendToAddress(newAddress.result, 0.00001, function(err, txid) { 11 | if (err) 12 | throw Error(JSON.stringify(err)); 13 | console.log("TXID: " + txid.result); 14 | 15 | agent.getTransaction(txid.result, function (err, transaction) { 16 | if (err) 17 | throw Error(JSON.stringify(err)); 18 | console.log(transaction.result); 19 | }); 20 | }); 21 | 22 | }); 23 | -------------------------------------------------------------------------------- /src/18_3_walletinfo.js: -------------------------------------------------------------------------------- 1 | const RpcAgent = require('bcrpc'); 2 | agent = new RpcAgent({port: 18332, user: 'StandUp', pass: '6305f1b2dbb3bc5a16cd0f4aac7e1eba'}); 3 | 4 | agent.getReceivedByAddress('tb1q04q2wzlhfqlrnz95ynfj7gp4t3yynrj0542smv', function (err, addressInfo) { 5 | if (err) 6 | throw Error(JSON.stringify(err)); 7 | console.log(addressInfo.result); 8 | }); 9 | 10 | agent.getWalletInfo(function (err, walletInfo) { 11 | if (err) 12 | throw Error(JSON.stringify(err)); 13 | console.log(walletInfo.result); 14 | }); 15 | -------------------------------------------------------------------------------- /src/18_4_getinfo.py: -------------------------------------------------------------------------------- 1 | from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException 2 | from pprint import pprint 3 | import logging 4 | 5 | logging.basicConfig() 6 | logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG) 7 | # rpc_user and rpc_password are set in the bitcoin.conf file 8 | rpc_user = "StandUp" 9 | rpc_pass = "6305f1b2dbb3bc5a16cd0f4aac7e1eba" 10 | rpc_host = "127.0.0.1" 11 | rpc_client = AuthServiceProxy(f"http://{rpc_user}:{rpc_pass}@{rpc_host}:18332", 12 | timeout=120) 13 | 14 | block_count = rpc_client.getblockcount() 15 | print("---------------------------------------------------------------") 16 | print("Block Count:", block_count) 17 | print("---------------------------------------------------------------\n") 18 | 19 | blockhash = rpc_client.getblockhash(block_count) 20 | block = rpc_client.getblock(blockhash) 21 | 22 | nTx = block['nTx'] 23 | if nTx > 10: 24 | it_txs = 10 25 | list_tx_heading = "First 10 transactions: " 26 | else: 27 | it_txs = nTx 28 | list_tx_heading = f"All the {it_txs} transactions: " 29 | print("---------------------------------------------------------------") 30 | print("BLOCK: ", block_count) 31 | print("-------------") 32 | print("Block Hash...: ", blockhash) 33 | print("Merkle Root..: ", block['merkleroot']) 34 | print("Block Size...: ", block['size']) 35 | print("Block Weight.: ", block['weight']) 36 | print("Nonce........: ", block['nonce']) 37 | print("Difficulty...: ", block['difficulty']) 38 | print("Number of Tx.: ", nTx) 39 | print(list_tx_heading) 40 | print("---------------------") 41 | i = 0 42 | while i < it_txs: 43 | print(i, ":", block['tx'][i]) 44 | i += 1 45 | print("---------------------------------------------------------------\n") 46 | -------------------------------------------------------------------------------- /src/18_4_sendtx.py: -------------------------------------------------------------------------------- 1 | from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException 2 | from pprint import pprint 3 | import logging 4 | 5 | #logging.basicConfig() 6 | #logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG) 7 | # rpc_user and rpc_password are set in the bitcoin.conf file 8 | rpc_user = "StandUp" 9 | rpc_pass = "6305f1b2dbb3bc5a16cd0f4aac7e1eba" 10 | rpc_host = "127.0.0.1" 11 | rpc_client = AuthServiceProxy(f"http://{rpc_user}:{rpc_pass}@{rpc_host}:18332", timeout=120) 12 | 13 | print("Creating a Transaction") 14 | 15 | ## 0. Create New Addresses 16 | 17 | new_address = rpc_client.getnewaddress("Learning-Bitcoin-from-the-Command-Line") 18 | new_change_address = rpc_client.getrawchangeaddress() 19 | 20 | ## 1. Select UTXO 21 | 22 | utxos = rpc_client.listunspent() 23 | selected_utxo = utxos[0] # we select the first utxo here 24 | utxo_address = selected_utxo['address'] 25 | utxo_txid = selected_utxo['txid'] 26 | utxo_vout = selected_utxo['vout'] 27 | utxo_amt = float(selected_utxo['amount']) 28 | # here we are sending bitcoins to an address generated by us in our own wallet. 29 | recipient_address = new_address 30 | recipient_amt = utxo_amt / 2 # sending half coins to recipient 31 | miner_fee = 0.00000300 # choose appropriate fee based on your tx size 32 | change_address = new_change_address 33 | change_amt = float('%.8f'%((utxo_amt - recipient_amt) - miner_fee)) 34 | print("---------------------------------------------------------------") 35 | print("Transaction Details:") 36 | print("-------------------") 37 | print("UTXO Address.......: ", utxo_address) 38 | print("UTXO Txid..........: ", utxo_txid) 39 | print("Vector ID of Output: ", utxo_vout) 40 | print("UTXO Amount........: ", utxo_amt) 41 | print("Tx Amount..........: ", recipient_amt) 42 | print("Recipient Address..: ", recipient_address) 43 | print("Change Address.....: ", change_address) 44 | print("Miner Fee..........: ", miner_fee) 45 | print("Change Amount......: ", change_amt) 46 | print("---------------------------------------------------------------\n") 47 | 48 | ## 2. Create Raw Transaction 49 | txids_vouts = [{"txid": utxo_txid, "vout": utxo_vout}] 50 | addresses_amts = {f"{recipient_address}": recipient_amt, f"{change_address}": change_amt} 51 | unsigned_tx_hex = rpc_client.createrawtransaction(txids_vouts, addresses_amts) 52 | print("---------------------------------------------------------------") 53 | print("Unsigned Transaction Hex: ", unsigned_tx_hex) 54 | print("---------------------------------------------------------------\n") 55 | 56 | ## 3. Sign Raw Transaction 57 | address_priv_key = [] # list of priv keys of each utxo 58 | address_priv_key.append(rpc_client.dumpprivkey(utxo_address)) 59 | signed_tx = rpc_client.signrawtransactionwithkey(unsigned_tx_hex, address_priv_key) 60 | print("---------------------------------------------------------------") 61 | print("Signed Transaction: ") 62 | print("----------------------") 63 | pprint(signed_tx) 64 | print("---------------------------------------------------------------\n") 65 | 66 | ## 4. Broadcast Transaction 67 | send_tx = rpc_client.sendrawtransaction(signed_tx['hex']) 68 | print("---------------------------------------------------------------") 69 | print("TXID of sent transaction: ", send_tx) 70 | -------------------------------------------------------------------------------- /src/18_4_walletinfo.py: -------------------------------------------------------------------------------- 1 | from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException 2 | from pprint import pprint 3 | import logging 4 | 5 | #logging.basicConfig() 6 | #logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG) 7 | # rpc_user and rpc_password are set in the bitcoin.conf file 8 | rpc_user = "StandUp" 9 | rpc_pass = "6305f1b2dbb3bc5a16cd0f4aac7e1eba" 10 | rpc_host = "127.0.0.1" 11 | rpc_client = AuthServiceProxy(f"http://{rpc_user}:{rpc_pass}@{rpc_host}:18332", 12 | timeout=120) 13 | 14 | # Look Up Wallet 15 | 16 | wallet_info = rpc_client.getwalletinfo() 17 | print("---------------------------------------------------------------") 18 | print("Wallet Info:") 19 | print("-----------") 20 | pprint(wallet_info) 21 | print("---------------------------------------------------------------\n") 22 | 23 | ## List UTXOs 24 | 25 | utxos = rpc_client.listunspent() 26 | print("Utxos: ") 27 | print("-----") 28 | pprint(utxos) 29 | print("------------------------------------------\n") 30 | 31 | ## Select a UTXO - first one selected here 32 | 33 | utxo_txid = utxos[0]['txid'] 34 | 35 | ## Get UTXO Hex 36 | 37 | utxo_hex = rpc_client.gettransaction(utxo_txid)['hex'] 38 | 39 | ## Get tx Details 40 | 41 | utxo_tx_details = rpc_client.decoderawtransaction(utxo_hex) 42 | print("Details of Utxo with txid:", utxo_txid) 43 | print("---------------------------------------------------------------") 44 | print("UTXO Details:") 45 | print("------------") 46 | pprint(utxo_tx_details) 47 | print("---------------------------------------------------------------\n") 48 | -------------------------------------------------------------------------------- /src/18_5_main-getinfo.rs: -------------------------------------------------------------------------------- 1 | use bitcoincore_rpc::{Auth, Client, RpcApi}; 2 | 3 | fn main() { 4 | let rpc = Client::new( 5 | "http://localhost:18332".to_string(), 6 | Auth::UserPass("StandUp".to_string(), "6305f1b2dbb3bc5a16cd0f4aac7e1eba" 7 | .to_string()), 8 | ) 9 | .unwrap(); 10 | 11 | let mining_info = rpc.get_mining_info().unwrap(); 12 | println!("{:#?}", mining_info); 13 | 14 | let hash = rpc.get_best_block_hash().unwrap(); 15 | let block = rpc.get_block(&hash).unwrap(); 16 | println!("{:?}", block); 17 | 18 | let _ = rpc.stop().unwrap(); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/18_5_main-sendtx.rs: -------------------------------------------------------------------------------- 1 | use bitcoincore_rpc::{json, Auth, Client, RpcApi}; 2 | use bitcoincore_rpc::bitcoin::{Amount}; 3 | use std::collections::HashMap; 4 | 5 | fn main() { 6 | let rpc = Client::new( 7 | "http://localhost:18332".to_string(), 8 | Auth::UserPass("StandUp".to_string(), "6305f1b2dbb3bc5a16cd0f4aac7e1eba".to_string()), 9 | ) 10 | .unwrap(); 11 | 12 | let balance = rpc.get_balance(None, None).unwrap(); 13 | println!("Balance: {:?} BTC", balance.as_btc()); 14 | 15 | // 0. Generate a recipient address 16 | 17 | let myaddress = rpc 18 | .get_new_address(Option::Some("BlockchainCommons"), Option::Some(json::AddressType::Bech32)) 19 | .unwrap(); 20 | println!("address: {:?}", myaddress); 21 | 22 | // 1. List UTXOs 23 | 24 | let unspent = rpc 25 | .list_unspent( 26 | None, 27 | None, 28 | None, 29 | None, 30 | Option::Some(json::ListUnspentQueryOptions { 31 | minimum_amount: Option::Some(Amount::from_btc(0.01).unwrap()), 32 | maximum_amount: None, 33 | maximum_count: None, 34 | minimum_sum_amount: None, 35 | }), 36 | ) 37 | .unwrap(); 38 | 39 | let selected_tx = &unspent[0]; 40 | 41 | println!("selected unspent transaction: {:#?}", selected_tx); 42 | 43 | // 2. Populate Variables 44 | 45 | let selected_utxos = json::CreateRawTransactionInput { 46 | txid: selected_tx.txid, 47 | vout: selected_tx.vout, 48 | sequence: None, 49 | }; 50 | 51 | let unspent_amount = selected_tx.amount; 52 | let amount = unspent_amount - Amount::from_btc(0.00001).unwrap(); 53 | 54 | let mut output = HashMap::new(); 55 | output.insert( 56 | myaddress.to_string(), 57 | amount, 58 | ); 59 | 60 | // 3. Create Raw Transaction 61 | 62 | let unsigned_tx = rpc 63 | .create_raw_transaction(&[selected_utxos], &output, None, None) 64 | .unwrap(); 65 | 66 | println!("unsigned tx {:#?}", unsigned_tx); 67 | 68 | // 4. Sign Transaction 69 | 70 | let signed_tx = rpc 71 | .sign_raw_transaction_with_wallet(&unsigned_tx, None, None) 72 | .unwrap(); 73 | 74 | println!("signed tx {:?}", signed_tx.transaction().unwrap()); 75 | 76 | // 5. Send Transaction 77 | 78 | let txid_sent = rpc 79 | .send_raw_transaction(&signed_tx.transaction().unwrap()) 80 | .unwrap(); 81 | 82 | println!("{:?}", txid_sent); 83 | 84 | // 6. Cleanup 85 | 86 | let unspent_amount = selected_tx.amount; 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/18_6_getinfo.playground: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | func makeCommand(method: String, param: Any, completionHandler: @escaping (Any?) -> Void) -> Void { 4 | 5 | // 1. Build a URL 6 | 7 | let testnetRpcPort = "18332" 8 | let nodeIp = "127.0.0.1:\(testnetRpcPort)" 9 | let rpcusername = "oIjA53JC2u" 10 | let rpcpassword = "ebVCeSyyM0LurvgQyi0exWTqm4oU0rZU" 11 | let walletName = "" 12 | let walletUrl = "http://\(rpcusername):\(rpcpassword)@\(nodeIp)/\(walletName)" 13 | 14 | let url = URL(string: walletUrl) 15 | 16 | // 2. Build a Request 17 | 18 | var request = URLRequest(url: url!) 19 | request.httpMethod = "POST" 20 | request.setValue("text/plain", forHTTPHeaderField: "Content-Type") 21 | request.httpBody = "{\"jsonrpc\":\"1.0\",\"id\":\"curltest\",\"method\":\"\(method)\",\"params\":[\(param)]}".data(using: .utf8) 22 | 23 | // 3. Build a Session 24 | 25 | let session = URLSession(configuration: .default) 26 | let task = session.dataTask(with: request as URLRequest) { data, response, error in 27 | 28 | do { 29 | 30 | 31 | if error != nil { 32 | 33 | //Handle the error 34 | 35 | } else { 36 | 37 | if let urlContent = data { 38 | 39 | do { 40 | 41 | let json = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableLeaves) as! NSDictionary 42 | if let errorCheck = json["error"] as? NSDictionary { 43 | 44 | if let errorMessage = errorCheck["message"] as? String { 45 | 46 | print("FAILED") 47 | print(errorMessage) 48 | 49 | } 50 | 51 | } else { 52 | 53 | let result = json["result"] 54 | completionHandler(result) 55 | 56 | } 57 | 58 | } catch { 59 | 60 | //Handle error here 61 | 62 | } 63 | 64 | } 65 | 66 | } 67 | 68 | } 69 | 70 | } 71 | 72 | task.resume() 73 | 74 | } 75 | 76 | // Test getblockchaininfo 77 | 78 | var method = "getblockchaininfo" 79 | var param = "" 80 | 81 | makeCommand(method: method,param: param) { result in 82 | 83 | print(result!) 84 | let blockinfo = result as! NSDictionary 85 | let block = blockinfo["blocks"] as! NSNumber 86 | 87 | // Test getblockchash 88 | 89 | method = "getblockhash" 90 | makeCommand(method: method,param: block) { result in 91 | print("Blockhash for \(block) is \(result!)") 92 | } 93 | 94 | } 95 | --------------------------------------------------------------------------------