Skip to content

Commit

Permalink
继续优化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
yangyile committed Dec 13, 2024
1 parent 12ddc3c commit 6170ee3
Show file tree
Hide file tree
Showing 11 changed files with 486 additions and 130 deletions.
73 changes: 73 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
name: create-release

on:
push:
branches:
- main # 监听 main 分支的 push 操作(编译和测试/代码检查)
tags:
- 'v*' # 监听以 'v' 开头的标签的 push 操作(发布 Release)

jobs:
lint:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v5
with:
go-version: "1.23.x"
- uses: actions/checkout@v4
- name: golangci-lint
uses: golangci/golangci-lint-action@v6
with:
version: latest

test:
runs-on: ubuntu-latest
strategy:
matrix:
go: [ "1.22.x", "1.23.x" ]
steps:
- uses: actions/checkout@v4

- uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go }}

- name: Run test
run: make test COVERAGE_DIR=/tmp/coverage

- name: Send goveralls coverage
uses: shogo82148/actions-goveralls@v1
with:
path-to-profile: /tmp/coverage/combined.txt
flag-name: Go-${{ matrix.go }}
parallel: true

check-coverage:
name: Check coverage
needs: [ test ]
runs-on: ubuntu-latest
steps:
- uses: shogo82148/actions-goveralls@v1
with:
parallel-finished: true

# 发布 Release
release:
name: Release a new version
needs: [ lint, test ]
runs-on: ubuntu-latest
# 仅在推送标签时执行
if: ${{ success() && startsWith(github.ref, 'refs/tags/v') }}
steps:
# 1. 检出代码
- name: Checkout code
uses: actions/checkout@v4

# 2. 创建 Release 和上传源码包
- name: Create Release
uses: softprops/action-gh-release@v2
with:
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 yangyile-yyle88

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
10 changes: 10 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
COVERAGE_DIR ?= .coverage

# cp from: https://github.com/yyle88/gormcngen/blob/5f75d814c71ec306b276a804c134de6655913951/Makefile#L4
test:
@-rm -r $(COVERAGE_DIR)
@mkdir $(COVERAGE_DIR)
make test-with-flags TEST_FLAGS='-v -race -covermode atomic -coverprofile $$(COVERAGE_DIR)/combined.txt -bench=. -benchmem -timeout 20m'

test-with-flags:
@go test $(TEST_FLAGS) ./...
173 changes: 137 additions & 36 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,66 +1,167 @@
[![GitHub Workflow Status (branch)](https://img.shields.io/github/actions/workflow/status/yyle88/gobtcsign/release.yml?branch=main&label=BUILD)](https://github.com/yyle88/gobtcsign/actions/workflows/release.yml?query=branch%3Amain)
[![GoDoc](https://pkg.go.dev/badge/github.com/yyle88/gobtcsign)](https://pkg.go.dev/github.com/yyle88/gobtcsign)
[![Coverage Status](https://img.shields.io/coveralls/github/yyle88/gobtcsign/master.svg)](https://coveralls.io/github/yyle88/gobtcsign?branch=main)
![Supported Go Versions](https://img.shields.io/badge/Go-1.22%2C%201.23-lightgrey.svg)
[![GitHub Release](https://img.shields.io/github/release/yyle88/gobtcsign.svg)](https://github.com/yyle88/gobtcsign/releases)
[![Go Report Card](https://goreportcard.com/badge/github.com/yyle88/gobtcsign)](https://goreportcard.com/report/github.com/yyle88/gobtcsign)

# gobtcsign

## 第一步创建钱包
`gobtcsign` is a concise and efficient Bitcoin transaction signing library designed to help developers quickly build, sign, and verify Bitcoin transactions.

`gobtcsign` is a Golang package that simplifies BTC/DOGECOIN transaction signing and serves as a gateway for developers to explore BTC blockchain knowledge.

---

## CHINESE README

[中文说明](README.zh.md)

---

## Installation

```bash
go get github.com/yyle88/gobtcsign
```

---

## Features

Here are the core features provided by `gobtcsign`:

1. **Transaction Construction**: Efficiently construct transactions with support for multiple inputs and outputs, including automatic change calculation. A dynamic fee adjustment feature allows users to control transaction costs.
2. **Transaction Size Estimation**: Estimate the virtual size (vSize) of transactions based on the number and type of inputs/outputs. This helps developers set appropriate fee rates based on real-time conditions.
3. **Transaction Signing**: Compatible with multiple address types, including P2PKH, P2SH, and SegWit. Developers can use private keys to sign transaction inputs.
4. **Signature Verification**: Ensure transaction signatures are valid, reducing the risk of rejection by the network due to signature issues.
5. **Transaction Serialization**: Serialize signed transactions into hexadecimal strings for direct broadcasting to the Bitcoin network.

---

## Dependencies

`gobtcsign` relies on the following key modules:

- **github.com/btcsuite/btcd**: Implements Bitcoin's core protocol and serves as the foundation for building and parsing transactions.
- **github.com/btcsuite/btcd/btcec/v2**: Handles elliptic curve cryptography for key management and signature generation/verification.
- **github.com/btcsuite/btcd/btcutil**: Provides utilities for encoding/decoding Bitcoin addresses and other common Bitcoin operations.
- **github.com/btcsuite/btcd/chaincfg/chainhash**: Offers hash calculations and chain-related utilities.
- **github.com/btcsuite/btcwallet/wallet/txauthor**: Constructs transaction inputs/outputs and automatically handles change.
- **github.com/btcsuite/btcwallet/wallet/txrules**: Defines transaction rules, including minimum fee calculations and other constraints.
- **github.com/btcsuite/btcwallet/wallet/txsizes**: Calculates the virtual size (vSize) of transactions, enabling dynamic fee adjustments.

`gobtcsign` avoids using packages outside the `github.com/btcsuite` suite. Even so, you should never use this library directly for signing transactions without careful review to avoid potential malicious code that could collect your private keys. The best practice is to **fork the project** or copy the relevant code into your project while thoroughly reviewing the code and configuring strict network whitelists for your servers.

---

## Usage Steps

1. **Initialize Transaction Parameters**: Define transaction inputs (UTXOs), output target addresses, and amounts. Configure Replace-By-Fee (RBF) options as needed.
2. **Estimate Transaction Size and Fees**: Use the library's methods to estimate transaction size and set appropriate fees based on real-time fee rates.
3. **Generate Unsigned Transactions**: Build transactions using the defined parameters.
4. **Sign Transactions**: Sign transaction inputs using the corresponding private keys.
5. **Validate and Serialize**: Verify the signature's validity and serialize the transaction into a hexadecimal string for broadcasting.

---

## Demos

[BTC-SIGN](internal/demos/signbtc/main/main.go) [DOGECOIN-SIGN](internal/demos/signdoge/main/main.go)

---

## Notes

1. **Private Key Security**: Never expose private keys in production environments. Only use demo data for development or testing purposes.
2. **Fee Settings**: Set transaction fees reasonably based on size and network congestion to avoid rejection by miners.
3. **Change Address**: Ensure leftover funds are returned to your address as change to avoid loss of funds.
4. **Network Configuration**: Properly configure network parameters (e.g., `chaincfg.TestNet3Params`) for TestNet or MainNet usage.

---

## Getting Started with Bitcoin (BTC)

Using `gobtcsign`, here is a simple introduction to Bitcoin (`BTC`):

### Step 1 - Create a Wallet

Create a test wallet using **offline tools**. For example, see [create_wallet_test.go](create_wallet_test.go).

Avoid using online tools to create wallets, as they could expose your private key to unauthorized parties.

Blockchain wallets are created offline, and you can use any offline tool you prefer for this purpose. **Generating a private key online is insecure and should be avoided.**

### Step 2 - Obtain Test Coins from a Faucet

Look for a Bitcoin faucet online to receive some test coins. This will provide the UTXOs you need for transaction testing.

### Step 3 - Sign and Send a Transaction

Once you have UTXOs from the faucet, you can construct and send transactions.

In practice, you need extra features like block crawling to automatically get your UTXOs. Without these features, you can't fully automate sending transactions.

You can use blockchain explorers and program code to send transactions manually, while for automated transactions, block crawling is required.

### Additional - Use DOGE to Learn BTC

创建个测试钱包即可
Since Dogecoin (DOGE) is derived from Litecoin (LTC), which itself is derived from Bitcoin (BTC), this library also supports DOGE signing.

注意不要使用在线的网页创建钱包,否则私钥容易被别人收集。
While Litecoin signing hasn't been tested, you can try it if you want.

## 第二步找水龙头
DOGE provides an excellent environment for learning due to its faster block times, allowing 6-block confirmation in just a few minutes. This makes testing and iteration more efficient compared to BTC, which requires around an hour for 6-block confirmation.

测试币水头龙,在网上多找找总会有的,让水龙头给自己弄点测试币,这样自己就有了所谓的UTXO啦
BTC has richer resources and greater adoption, making it more beneficial for learning blockchain concepts. Since DOGE mimics BTC, testing DOGE logic can often reveal BTC-related issues. Supporting both BTC and DOGE is a practical choice for developers.

## 第三步尝试签名和发个交易
### Important - Don’t Forget Change Outputs

通过水龙头给的UTXO就可以发交易
Forgetting to include change outputs can lead to significant losses. Here is an example:

当然实际上还是需要你具备其它能力,比如爬块技术,这样才能得到你的UTXO,否则还是不能发交易的
- Transaction at block height **818087**
- Hash: `b5a2af5845a8d3796308ff9840e567b14cf6bb158ff26c999e6f9a1f5448f9aa`
- The sender transferred **139.42495946 BTC** (worth $5,217,651), but the recipient only received **55.76998378 BTC** (worth $2,087,060).
- The remaining **83.65497568 BTC** (worth $3,130,590) was lost as miner fees.

通过区块链浏览器,以及代码,能够手动发交易,但自动化发交易还是依赖于爬块。
This is a mistake that would be deeply regrettable and must be avoided.

## 其它
---

由于狗狗币是通过LTC衍生来的,而LTC是通过BTC衍生来的,因此这个包也能用于狗狗币的签名
## DISCLAIMER

至于莱特币签名,没有尝试过,或许也是可以的
Crypto coin, at its core, is nothing but a scam. It thrives on the concept of "air coins"—valueless digital assets—to exploit the hard-earned wealth of ordinary people, all under the guise of innovation and progress. This ecosystem is inherently devoid of fairness or justice.

该包中有些狗狗币签名的样例,这是因为狗狗币的出块速度快,只几分钟就能达到6个块的确认高度,做实验或者测试相对比较便捷。
而BTC的确认达到6个块需要1小时甚至更久些,在做开发时就不太方便测试和迭代逻辑。
但BTC的资料多些,也更主流,有利于学习区块链相关的知识。
DOGE纯的模仿BTC的,逻辑99%都是互通的,因此在开发时,测试DOGE逻辑也能发现BTC的问题。
因此同时接BTC+DOGECOIN也是不错的选择。
For the elderly, cryptocurrencies present significant challenges and risks. The so-called "high-tech" façade often excludes them from understanding or engaging with these tools. Instead, they become easy targets for financial exploitation, stripped of the resources they worked a lifetime to accumulate.

## 注意
The younger generation faces a different but equally insidious issue. By the time they have the opportunity to engage, the early adopters have already hoarded the lion’s share of resources. The system is inherently tilted, offering little chance for new entrants to gain a fair footing.

该项目几乎没有引用除 `github.com/btcsuite` 以外的其它包,但假如您要签名交易时,依然不应该直接使用该项目,避免添加恶意代码收集您的私钥。正确的做法是fork项目,最正确的做法是拷贝代码到自己的项目里,而不要引用其他项目,而且要严格审查代码。
The idea that cryptocurrencies like BTC, ETH, or TRX could replace global fiat currencies is nothing more than a pipe dream. This notion serves only as the shameless fantasy of early adopters, particularly those from the 1980s generation, who hoarded significant amounts of crypto coin before the general public even had an opportunity to participate.

注意不要忘记找零否则将会有重大损失,详见下面的案例。
Ask yourself this: would someone holding thousands, or even tens of thousands, of Bitcoin ever genuinely believe the system is fair? The answer is unequivocally no. These systems were never designed with fairness in mind but rather to entrench the advantages of a select few.

发送方发送了139.42495946 BTC,价值5,217,651美元,而接收方仅收到了55.76998378 BTC,价值2,087,060美元。
剩余的83.65497568 BTC则是矿工费用,价值3,130,590美元。
这笔交易发生在区块高度818087里面。
哈希值:b5a2af5845a8d3796308ff9840e567b14cf6bb158ff26c999e6f9a1f5448f9aa
The rise of cryptocurrencies is not the endgame. It is inevitable that new innovations will emerge, replacing these deeply flawed systems. At this moment, my interest lies purely in understanding the underlying technology—nothing more, nothing less.

这是一笔巨大的损失,需要特别重视,避免重蹈覆辙。
This project exists solely for the purpose of technical learning and exploration. The author of this project maintains a firm and unequivocal stance of *staunch resistance to cryptocurrencies*.

## 其它的免责声明
---

数字货币都是骗局
## License

都是以空气币掠夺平民财富
`gobtcsign` is open-source and released under the MIT License. See the [LICENSE](LICENSE) file for more information.

没有公平正义可言
---

数字货币对中老年人是极不友好的,因为他们没有机会接触这类披着高科技外衣的割韭菜工具
## Support

数字货币对青少年也是极不友好的,因为当他们接触的时候,前面的人已经占据了大量的资源
Welcome to contribute to this project by submitting pull requests or reporting issues.

因此妄图以数字货币,比如稍微主流的 BTC ETH TRX 代替世界货币的操作,都是不可能实现的
If you find this package helpful, give it a star on GitHub!

都不过是早先持有数字货币的八零后们的无耻幻想
**Thank you for your support!**

扪心自问,持有几千甚至数万个比特币的人会觉得公平吗,其实不会的
**Happy Coding with `gobtcsign`!** 🎉

因此未来还会有新事物来代替它们,而我现在也不过只是了解其中的技术,仅此而已。
Give me stars. Thank you!!!

该项目作者坚定持有“坚决抵制数字货币”的立场。
## See stars
[![see stars](https://starchart.cc/yyle88/gobtcsign.svg?variant=adaptive)](https://starchart.cc/yyle88/gobtcsign)
Loading

0 comments on commit 6170ee3

Please sign in to comment.