go-bitfs

module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2026 License: AGPL-3.0

README

go-bitfs

go-bitfs is the source of truth for the BitFS Wire Protocol v1 Go implementation: file exchange, arbitration, and 2-of-3 MultisigPool settlement. The implementation uses strict deterministic CBOR and preserves the exact signed bytes required for offline verification.

The protocol is documented in the multilingual Docusaurus site. English is the normative website language; Simplified Chinese is maintained under website/i18n/zh-CN/.

Step Specification Requirements and intent
001 Quote credential Requirements
002 Pool opening Requirements
003 Content request Requirements
004 Content delivery Requirements
005 Cumulative payment Requirements
006 Pool close Requirements
007 Seller arbitration Requirements
008 Buyer arbitrated content retrieval Requirements

Step 008 is read-only content recovery from arbiter custody. It is not a buyer arbitration close: when the seller is unreachable, the buyer either waits or broadcasts its presigned RefundTx after nLockTime.

The current CDDL is under spec/v1/; retired iterations are archived under spec/legacy/. Every complete wire message starts with [protocol.WireVersion, wire_kind, ...] and travels as a parsed wire.Artifact whose Bytes() returns an immutable copy of the exact bytes. Transaction scripts, fees, signatures, and state construction are delegated to the published github.com/bsv8/MultisigPool/v4 implementation. Network, queue, WebSocket, database adapters, time sources, and block-height sources remain application-owned interfaces supplied explicitly as protocol.Facts{Now, BlockHeight} per call.

Quick start

The only recommended path is the role workflow API. Keys enter through one constrained signer port (protocol.Signer; local software keys use protocol.NewPrivateKeySigner), time and height enter through one explicit facts value, and every outbound message is an exact-bytes wire.Artifact that the application persists before sending:

// ---- 步骤 1:三方密钥 → 受约束 Signer(唯一密钥托管端口)。----
signerSeller, err := protocol.NewPrivateKeySigner(sellerKey) // sellerKey 为 *ec.PrivateKey
signerBuyer, err := protocol.NewPrivateKeySigner(buyerKey)

// ---- 步骤 2:角色 workflow 只持有 Signer;无存储、无时钟、无网络。----
sellerWf, err := seller.NewWorkflow(signerSeller)
buyerWf, err := buyer.NewWorkflow(signerBuyer)

// ---- 步骤 3:显式事实(时间 + 高度)由调用方观测并传入;SDK 不读钟、不查节点。----
facts := protocol.Facts{Now: observedTimeUTC, BlockHeight: 900000}

// ---- 步骤 4(卖方):签署 001 报价,得到待发送 Artifact。----
qr, err := sellerWf.CreateQuote(ctx, facts, seller.QuoteDraft{
    SeedHash:                   seedHash,
    BuyerPublicKey:             buyerPubKey,
    SeedPriceSatoshis:          100,
    FullBlockPriceSatoshis:     1000,
    FileSizeBytes:              uint64(len(fileBytes)),
    QuoteExpiresAtUnixSeconds:  facts.Now.Add(time.Hour).Unix(),
    SupportedArbiterPublicKeys: [][]byte{arbiterPubKey},
    RecommendedFilename:        "file.bin", // 先 sanitize 再进入签名条款
})
rawKind1 := qr.Outbound.Bytes() // 应用先持久化 exact Kind 1 bytes 再发送

// ---- 步骤 5(买方):从 exact bytes 验收,得到不可变 VerifiedQuote。----
vq, err := buyerWf.AcceptQuote(ctx, facts, rawKind1)

// ---- 步骤 6–7:开池(买方 PreparePoolOpening → 卖方 PreparePoolOpening
//      → 买方 CompletePoolOpening → PrepareFundingDelivery → 卖方
//      VerifyFundingDelivery),每个 Result 都先持久化 Checkpoint 再发送
//      Outbound;广播边界属于应用。----

// ---- 步骤 8–10:一轮购买。----
rc, err := buyerWf.RequestContent(ctx, facts, buyer.RequestContentCommand{
    Quote: vq, Pool: poolCheckpoint, ContentHashes: hashes,
    DeliveryDeadline: deadlineUnixSeconds, Seed: seedBytes,
})                                   // → Kind 5 Artifact + AuthorizationCheckpoint
dr, err := sellerWf.DeliverContent(ctx, facts, seller.DeliveryCommand{
    Quote: signedQuote, Pool: sellerPool, RequestRaw: rawKind5,
    ContentPayloads: payloads, Seed: seedBytes,
})                                   // → Kind 6 Artifact + DeliveryCheckpoint
pp, err := buyerWf.VerifyDeliveryAndPreparePayment(ctx, facts, buyer.VerifyDeliveryCommand{
    Quote: vq, Pool: poolCheckpoint, Request: rc.Checkpoint,
    DeliveryRaw: rawKind6, Seed: seedBytes,
})                                   // → 验证 payload + 唯一 Kind 7 凭证
cp, err := sellerWf.CompletePayment(ctx, facts, seller.PaymentCommand{
    Pool: sellerPool, Request: signedRequest, UpdateRaw: rawKind7,
    Checkpoint: dr.Checkpoint,
})                                   // → 完整付款交易 + 双方推进后的池 checkpoint

Error handling branches on stable categories, never on error text:

if _, err := buyerWf.AcceptQuote(ctx, facts, raw); err != nil {
    switch {
    case protocol.IsCode(err, protocol.CodeExpired):
        // 报价过期:按业务策略重新要报价。
    case protocol.IsCode(err, protocol.CodeInvalidSignature):
        // 卖方签名验证失败:拒绝该凭证。
    default:
        // 其余分类见 protocol.ErrorCode(malformed_wire、state_conflict 等)。
    }
}

Packages

  • protocol/: shared foundations — constrained Signer port (+ NewPrivateKeySigner), explicit Facts, typed IDs, structured errors with ErrorCode classification.
  • content/: quote and content credentials, seeds, hashes, pricing, and evidence validation (001/003/004), plus the immutable VerifiedQuote.
  • pool/: independent 002/005/006 settlement state machine and transaction engine with opaque verified values.
  • buyer/, seller/, arbiter/: role workflows — the only recommended entry path for applications.
  • arbitration/: pure 007/008 custody-evidence domain functions; wire/: typed encoders and strict decoders returning wire.Artifact values.

Run the test suite with:

go test ./...

Directories

Path Synopsis
Package arbiter 是 007/008 的 Arbiter 角色 API:持有固定受约束 Signer, 完成"先完整验证并持久化托管证据、再独立重建交易与 digest 后签名"的 Prepare-before-Sign 编排,以及时间无关的 008 取回鉴权/托管验证与 Kind 11 两分支构造。
Package arbiter 是 007/008 的 Arbiter 角色 API:持有固定受约束 Signer, 完成"先完整验证并持久化托管证据、再独立重建交易与 digest 后签名"的 Prepare-before-Sign 编排,以及时间无关的 008 取回鉴权/托管验证与 Kind 11 两分支构造。
Kind 10/11 buyer custody retrieval under the unified wire model.
Kind 10/11 buyer custody retrieval under the unified wire model.
demo
01_quote/01_build_quote command
Command seller builds a signed BitFS 001 file quote.
Command seller builds a signed BitFS 001 file quote.
01_quote/02_parse_quote command
Command buyer parses and verifies a BitFS 001 file quote.
Command buyer parses and verifies a BitFS 001 file quote.
02_pool_opening/0201_buyer_build_refund_request command
0201 是开池流程的第一个买方动作。
0201 是开池流程的第一个买方动作。
02_pool_opening/0202_seller_accept_refund_request command
0202 是开池流程的卖方接收动作。
0202 是开池流程的卖方接收动作。
02_pool_opening/0203_buyer_accept_refund_response command
0203 是开池流程的第二个买方动作,也是买方建立完整池证据的边界。
0203 是开池流程的第二个买方动作,也是买方建立完整池证据的边界。
02_pool_opening/0204_buyer_build_funding_delivery command
0204 是开池流程中公开完整 FundingTransactionRaw 的买方动作。
0204 是开池流程中公开完整 FundingTransactionRaw 的买方动作。
02_pool_opening/0205_seller_accept_funding_delivery command
0205 是开池流程的卖方收尾动作。
0205 是开池流程的卖方收尾动作。
03_content_request/01_build_request command
Command buyer builds a signed BitFS 003 content request.
Command buyer builds a signed BitFS 003 content request.
04_content_delivery/01_deliver_content command
Command seller delivers a content batch (BitFS 004).
Command seller delivers a content batch (BitFS 004).
05_cumulative_payment/01_accept_payment command
Command buyer and seller complete one cumulative payment (BitFS 003→004→005).
Command buyer and seller complete one cumulative payment (BitFS 003→004→005).
06_pool_close/01_close_pool command
Command buyer and seller perform an immediate pool close (BitFS 006).
Command buyer and seller perform an immediate pool close (BitFS 006).
07_arbitration/01_arbitrate_payment command
Command seller, arbiter complete an arbitrated payment (BitFS 007).
Command seller, arbiter complete an arbitrated payment (BitFS 007).
08_arbitration_content_retrieval/01_retrieve_content command
008 买方仲裁托管内容取回演示:Seller 与 Buyer 无法直连,但二者均能连接 Arbiter。
008 买方仲裁托管内容取回演示:Seller 与 Buyer 无法直连,但二者均能连接 Arbiter。
internal/demoenv
Package demoenv 负责加载各个 demo 共用的本地环境配置文件。
Package demoenv 负责加载各个 demo 共用的本地环境配置文件。
internal/fixture
Package fixture 提供结构稳定的内存 demo fixture。
Package fixture 提供结构稳定的内存 demo fixture。
internal/junglebus
Package junglebus 提供 demo 应用使用的轻量 JungleBus 客户端。
Package junglebus 提供 demo 应用使用的轻量 JungleBus 客户端。
internal/poolopening
Package poolopening 提供细粒度 002 开池 demo 共用的应用组装、交易辅助逻辑 和演示私有本地 checkpoint。
Package poolopening 提供细粒度 002 开池 demo 共用的应用组装、交易辅助逻辑 和演示私有本地 checkpoint。
docs
cddltool
Package cddltool implements a real parser and structural validator for the CDDL subset used by spec/v1/wire-messages.cddl.
Package cddltool implements a real parser and structural validator for the CDDL subset used by spec/v1/wire-messages.cddl.
internal
refundlock
Package refundlock holds the pure nLockTime comparison rules for MultisigPool refund templates.
Package refundlock holds the pure nLockTime comparison rules for MultisigPool refund templates.
Package pool contains the protocol-independent 2-of-3 settlement primitives used by 002, 005, and 006.
Package pool contains the protocol-independent 2-of-3 settlement primitives used by 002, 005, and 006.
Package protocol 是仓库唯一的共享基础层:强类型值、显式外部事实 Facts、 受约束 Signer 端口、typed ID、固定签名域与统一错误模型。
Package protocol 是仓库唯一的共享基础层:强类型值、显式外部事实 Facts、 受约束 Signer 端口、typed ID、固定签名域与统一错误模型。
Package wire 是 Wire v1 的 exact Artifact 层与严格分派入口。
Package wire 是 Wire v1 的 exact Artifact 层与严格分派入口。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL