Compact Target

medium · bitcoin, pow, difficulty

Compact Target (nBits)

Bitcoin encodes the proof-of-work target in a 4-byte "compact" format:

[exponent (1 byte)] [mantissa (3 bytes)]

The target is:

T = mantissa * 256^(exponent-3)

Functions

func CompactToTarget(bits uint32) *big.Int
func TargetToCompact(target *big.Int) uint32

Rules

  • Use unsigned arithmetic (ignore sign bit).
  • If target == 0, TargetToCompact should return 0.
  • TargetToCompact must produce the canonical encoding:
    • Let size = len(target.Bytes()).
    • Mantissa is the first 3 bytes of the big-endian target.
    • If the first mantissa byte has the high bit set (>= 0x80), shift the mantissa right by 8 and increment size.

Notes

  • You can use math/big for big integers.
  • Treat the hash as a big-endian integer when comparing against targets.
Run tests to see results
No issues detected