ledgerforge

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

LedgerForge

Build and Test

LedgerForge is an open-source double-entry ledger for applications that move money. Use it to record wallet transfers, billing activity, reservations and refunds through an HTTP API, a Go library or a local MCP server.

PostgreSQL stores the financial records. Redis supports queues and background workers. Search and observability services are optional. LedgerForge records money movement; connecting payment rails and defining your accounting model remain application responsibilities.

Accounting guarantees

  • Exact amounts: postings and balance arithmetic use integer units. Supply precise_amount with an explicit precision to avoid floating-point input loss; 1250 at precision 100 represents 12.50.
  • Double entry: each applied transfer debits its source and credits its destination by the same amount. Split transfers distribute that amount across their legs.
  • Immutable postings: corrections and refunds create linked transactions. Financial postings and accepted execution controls are preserved; customer metadata can be updated.
  • Idempotency by reference: reuse the same unique transaction reference after a timeout. Duplicate references are rejected; look up the original outcome instead of retrying with a new reference.

See ledger concepts for amount handling, balance semantics and asynchronous transaction states.

Quickstart: a balanced transfer

Requires Docker with Compose and Python 3. From a checkout:

git clone https://github.com/devaccuracy/ledgerforge.git
cd ledgerforge
./examples/quickstart/start.sh
./examples/quickstart/transfer.sh

This local-only demo builds the current checkout, generates a random master key, runs migrations and binds the API to 127.0.0.1:5001. It creates two USD balances and posts 12.50 synchronously using integer units. The source gets a bounded demo overdraft of 12.50; the result is -1250 and 1250 units, with equal total debits and credits. A retry with the same reference must leave those balances unchanged.

source: -1250 units
destination: 1250 units
total debits = total credits = 1250 units
reference retry: balances unchanged

Stop it with docker compose -p ledgerforge-demo -f examples/quickstart/compose.yaml down. See the example guide for the API payload, credentials and cleanup. These credentials and database defaults are for local use. Read the deployment guide before exposing a service.

Why LedgerForge

  • Exact money: integer postings and balance counters, preserved decimal request tokens, explicit precision and deterministic split allocation. Invalid monetary inputs are rejected before posting.
  • A verifiable ledger: read-only ledgerforge verify replays accounting evidence. Versioned audit chains and exportable checkpoints support audit verify --anchor against independently retained roots. See the verification guide for coverage and legacy limits.
  • Agent guardrails: per-key currency/precision limits, balance/ledger allowlists, durable daily reservations and approval holds enforced by the server. Delegated keys inherit restrictions and share ancestor budgets. Bind MCP to an API key and keep independent approver credentials outside the agent's authority. See agent safety and the executable policy example.
  • A hardened API: owner-bound key management, constrained delegation, authoritative revocation checks, bounded input and sanitized backend errors. Dedicated webhook signing secrets and destination controls protect outbound integrations. See security operations.
  • Tested invariants: exact-amount and allocation fuzz targets, generated PostgreSQL operation sequences, balance conservation checks and race tests for financial lifecycle and spending-capacity transitions.
  • Operational workflows: inflight reservations, partial settlement, refunds, split/bulk transfers, reconciliation, lineage, snapshots and optional search, metrics and OpenTelemetry. PostgreSQL retains financial truth while workers handle asynchronous execution and delivery.

Install

  • Release binaries: download ledgerforge and ledgerforge-mcp for Linux, macOS or Windows from GitHub Releases, then check the archive against checksums.txt (sha256sum -c checksums.txt --ignore-missing).
  • Container image: docker pull ghcr.io/devaccuracy/ledgerforge:1.0.0. The image contains both binaries; the release lists its digest and SBOMs.
  • From source: go install github.com/devaccuracy/ledgerforge/cmd/ledgerforge@v1.0.0 (Go 1.26.9 or later).

Run ledgerforge version to confirm what you installed, then follow the deployment guide and run ledgerforge migrate up before starting the server.

Run the published image locally

cp ledgerforge.example.json ledgerforge.json
# Replace server.secret_key with a random secret before starting.
# For example, generate one with: openssl rand -hex 32
docker compose up -d

The config explicitly enables authentication. API requests use the X-LedgerForge-Key header. Keep ledgerforge.json private and out of version control. The :main image tracks tested main-branch commits; pin a release tag or digest in production with LEDGERFORGE_IMAGE.

Documentation

Development

make verify
make test-integration
make vuln
make cover

See CONTRIBUTING.md for prerequisites and test isolation.

Community and license

Use GitHub issues for bugs and feature requests. Follow the Code of Conduct. Report vulnerabilities privately to security@ledgerforge.io.

Licensed under Apache 2.0. Required notices are in NOTICE.md.

Documentation

Overview

Package ledgerforge provides the stable public API for LedgerForge Core.

The implementation lives in an internal core package. This facade intentionally preserves the original github.com/devaccuracy/ledgerforge import path for existing applications while keeping the repository root focused on module metadata and public compatibility.

Index

Constants

View Source
const (
	InflightActionCommit  = core.InflightActionCommit
	InflightActionVoid    = core.InflightActionVoid
	IndexModeRefresh      = core.IndexModeRefresh
	BulkInflightCommit    = core.BulkInflightCommit
	BulkInflightVoid      = core.BulkInflightVoid
	GeneralLedgerID       = core.GeneralLedgerID
	LineageProviderKey    = core.LineageProviderKey
	LineageFundAllocation = core.LineageFundAllocation
	AllocationFIFO        = core.AllocationFIFO
	AllocationLIFO        = core.AllocationLIFO
	AllocationProp        = core.AllocationProp
	StatusQueued          = core.StatusQueued
	StatusApplied         = core.StatusApplied
	StatusScheduled       = core.StatusScheduled
	StatusRejected        = core.StatusRejected
	StatusInflight        = core.StatusInflight
	StatusVoid            = core.StatusVoid
	StatusCommit          = core.StatusCommit
	StatusStarted         = core.StatusStarted
	StatusInProgress      = core.StatusInProgress
	StatusCompleted       = core.StatusCompleted
	StatusFailed          = core.StatusFailed
)

Variables

View Source
var (
	ErrReindexInProgress = search.ErrReindexInProgress
	ErrReindexNotStarted = search.ErrReindexNotStarted
	ErrReindexClosed     = search.ErrReindexClosed
)

Reindex errors preserve admission and progress semantics across transports.

View Source
var ErrEntityNotFound = core.ErrEntityNotFound

ErrEntityNotFound indicates that a metadata target does not exist.

View Source
var ErrInflightActionQueued = core.ErrInflightActionQueued

ErrInflightActionQueued indicates a pending commit or void for a transaction.

View Source
var ErrQueueBackpressure = core.ErrQueueBackpressure

ErrQueueBackpressure indicates that the queue cannot safely accept more work.

View Source
var SQLFiles embed.FS = core.SQLFiles

SQLFiles contains the embedded migration files used by the LedgerForge CLI.

Functions

func ClassifyInflightError

func ClassifyInflightError(err error) string

ClassifyInflightError returns the public error code for an inflight operation.

func DocumentToIndexMap

func DocumentToIndexMap(document interface{}) (map[string]interface{}, error)

DocumentToIndexMap converts a search document into its index representation.

func IsDuplicateReferenceError

func IsDuplicateReferenceError(err error) bool

IsDuplicateReferenceError identifies a transaction reference conflict.

func IsInflightTransaction

func IsInflightTransaction(transaction *model.Transaction) bool

IsInflightTransaction reports whether a transaction is an inflight transaction.

func NewBalanceTracker

func NewBalanceTracker() *model.BalanceTracker

NewBalanceTracker creates a balance tracker.

Types

type Allocation

type Allocation = core.Allocation

type BalanceLineage

type BalanceLineage = core.BalanceLineage

type BatchJobResult

type BatchJobResult = core.BatchJobResult

type BulkInflightAction

type BulkInflightAction = core.BulkInflightAction

type BulkInflightItem

type BulkInflightItem = core.BulkInflightItem

type BulkInflightOutcome

type BulkInflightOutcome = core.BulkInflightOutcome

type BulkTransactionError

type BulkTransactionError = core.BulkTransactionError

type ChainProcessor

type ChainProcessor = core.ChainProcessor

func NewChainProcessor

func NewChainProcessor(service *LedgerForge) *ChainProcessor

NewChainProcessor creates the transaction hash-chain worker.

type ChainVerifyResult

type ChainVerifyResult = core.ChainVerifyResult

type IndexTask

type IndexTask = core.IndexTask

type IndexUpserter

type IndexUpserter = core.IndexUpserter

type InflightActionPayload

type InflightActionPayload = core.InflightActionPayload

type LedgerForge

type LedgerForge = core.LedgerForge

func NewLedgerForge

func NewLedgerForge(db database.IDataSource) (*LedgerForge, error)

NewLedgerForge initializes a LedgerForge instance using the provided datasource.

type LineageOutboxPayload

type LineageOutboxPayload = core.LineageOutboxPayload

type LineageOutboxProcessor

type LineageOutboxProcessor = core.LineageOutboxProcessor

func NewLineageOutboxProcessor

func NewLineageOutboxProcessor(service *LedgerForge) *LineageOutboxProcessor

NewLineageOutboxProcessor creates the lineage outbox worker.

type LineageSource

type LineageSource = core.LineageSource

type NewWebhook

type NewWebhook = core.NewWebhook

type ProviderBreakdown

type ProviderBreakdown = core.ProviderBreakdown

type Queue

type Queue = core.Queue

func NewQueue

func NewQueue(conf *config.Configuration, client *asynq.Client) *Queue

NewQueue creates the transaction queue service.

func NewQueueWithRedisClient

func NewQueueWithRedisClient(conf *config.Configuration, client *asynq.Client, redisClient redis.UniversalClient) *Queue

NewQueueWithRedisClient creates a queue with Redis memory backpressure checks.

type QueuedTransactionRecoveryProcessor

type QueuedTransactionRecoveryProcessor = core.QueuedTransactionRecoveryProcessor

func NewQueuedTransactionRecoveryProcessor

func NewQueuedTransactionRecoveryProcessor(service *LedgerForge) *QueuedTransactionRecoveryProcessor

NewQueuedTransactionRecoveryProcessor creates the queued-transaction recovery worker.

type RefundOptions

type RefundOptions = core.RefundOptions

type ReindexProgress

type ReindexProgress = search.ReindexProgress

type TransactionLineage

type TransactionLineage = core.TransactionLineage

type TransactionTypePayload

type TransactionTypePayload = core.TransactionTypePayload

Directories

Path Synopsis
api
cmd
ledgerforge command
ledgerforge-mcp command
ledgerforge-mcp exposes a LedgerForge deployment to MCP clients over stdio.
ledgerforge-mcp exposes a LedgerForge deployment to MCP clients over stdio.
internal
core
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
mcpserver
Package mcpserver exposes selected LedgerForge operations through the Model Context Protocol.
Package mcpserver exposes selected LedgerForge operations through the Model Context Protocol.
policy
Package policy implements server-enforced API-key spending admissions.
Package policy implements server-enforced API-key spending admissions.
tests
loadtest/tools command

Jump to

Keyboard shortcuts

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