How aead/chacha20 works
Project type and purpose
• This is an open-source Go library implementing the ChaCha stream cipher family (ChaCha20, XChaCha20, and reduced-round variants).
• Its core purpose is to provide high-performance encryption/decryption routines selectable at build/runtime based on CPU features.
File structure
• Top level:
• chacha20.go, chacha20_test.go – the public API and its tests
• chacha/ – internal subpackage containing multiple implementations
• .travis.yml, LICENSE, README.md – CI, licensing, and docs
• chacha/ subfolder: multiple .go and .s files organized by architecture (amd64, 386) and variant (AVX2, SSSE3, generic, reference).
• Tests are co-located with code (chacha/chacha_test.go).
Key insights from README
• Implements ChaCha20 with different nonces and round counts.
• Emphasizes runtime selection of the fastest available code path.
• No external services or databases—pure computation library.
Main components and their interactions
a. Public API Layer (chacha20.go)
• Exposes functions like XORKeyStream, NewCipher20, XChaCha20, etc.
• Selects the best implementation based on CPU feature detection.
b. Implementation Layer (chacha subpackage)
• Sub-components:
• Generic Go implementation (chacha_generic.go, chacha_ref.go)
• Architecture-specific optimized assembly (chacha_amd64.s + chacha_amd64.go, chachaAVX2_amd64.s, chacha_386.s + chacha_386.go)
• Constant tables and macros (const.s, macro.s)
• Selection logic in Go stubs calls into the chosen variant.
c. Test Harness
• Unit tests in both top level and subpackage verify correctness across all variants.
d. Build/CI
• Travis CI configured in .travis.yml to run go test across supported Go versions.
Architectural patterns and design principles
• Layered design: clear separation between Public API, generic implementation, and optimized backends.
• Strategy pattern: at init time, choose the best encryption “strategy” based on runtime CPU feature detection.
• Package scope: internal details hidden in the chacha subpackage; public interface kept minimal.
• Break the library into logical layers (API vs. implementations).
• Runtime selection logic (Strategy pattern).
• Architecture‐specific path as a separate component.
• Tests and build pipeline as supporting components.