npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@alexalves87/opentimestamps

v1.0.5

Published

A modern, zero-dependency TypeScript library for creating and verifying decentralized, blockchain-backed timestamps using the OpenTimestamps protocol.

Readme

@alexalves87/opentimestamps

CI npm version License: MIT

A modern, zero-dependency TypeScript library for creating and verifying decentralized, blockchain-backed timestamps using the OpenTimestamps protocol.

🇪🇸 Versión en Español | 🇬🇧 English Version


English Version

In a world of digital information, how can you prove a document, a piece of code, or a contract existed at a specific point in time, without relying on a centralized, trusted third party? The OpenTimestamps protocol provides a powerful, open-standard solution by anchoring cryptographic proofs of existence into the immutable Bitcoin blockchain.

@alexalves87/opentimestamps is the definitive tool for JavaScript and TypeScript developers to harness this power. It offers a clean, modern, async/await-based API to interact with the OpenTimestamps protocol, making it simple to create, upgrade, and verify timestamps in any Node.js or browser environment.

Features at a Glance

| Feature | Description | |---------|-------------| | Modern Asynchronous API | Built from the ground up with async/await for clean, readable, and non-blocking code. | | TypeScript Native | Written entirely in TypeScript, providing strong typing and superior IntelliSense out-of-the-box. | | Zero Dependencies | Lightweight and secure. Only one audited cryptographic dependency (@noble/hashes), reducing your node_modules footprint and attack surface. | | Universal Compatibility | Works seamlessly in both Node.js environments and modern web browsers. | | Robust and Reliable | Implements the full OpenTimestamps protocol for creating, upgrading, and verifying proofs. | | Well-Documented | Comprehensive documentation with clear examples for every common use case. | | 100% Test Coverage | 136 unit tests covering all critical functionality. |

How It Works: Core Concepts

The OpenTimestamps protocol provides a trust-minimized way to prove that data existed prior to a certain point in time. The process can be simplified into three main steps:

[Your Data] --(hash)--> [Fingerprint] --(stamp)--> [Incomplete Proof.ots] 
--(upgrade via Calendar Server)--> [Complete Proof.ots + Bitcoin Block]
  1. Stamp: You provide your data (e.g., a document or a file buffer). The library locally calculates a cryptographic hash (a unique "fingerprint") of this data, ensuring your data's privacy is preserved. This hash is then submitted to public "Calendar" servers. You immediately receive an incomplete timestamp proof (an .ots file).

  2. Upgrade: The Calendar servers aggregate your hash with many others into a Merkle Tree and anchor the root of this tree into a single Bitcoin transaction. This process can take from a few minutes to a few hours. Once confirmed on the blockchain, you can "upgrade" your incomplete proof. The library contacts the calendars to retrieve the full cryptographic path from your hash to the Bitcoin block header, creating a complete, self-contained proof.

  3. Verify: With the complete proof and the original data, anyone can independently verify the timestamp. The verification process re-applies the cryptographic operations in the proof and confirms that it correctly links to a valid block in the Bitcoin blockchain. This verification can be done without trusting the calendar servers or any other third party, relying only on the mathematical security of Bitcoin.

Installation

npm install @alexalves87/opentimestamps

Quick Start: Your First Timestamp in 60 Seconds

import { sha256 } from '@alexalves87/opentimestamps'
import { 
  serializeOTS, 
  deserializeOTS,
  createPendingAttestation 
} from '@alexalves87/opentimestamps'

// 1. Hash your document
const document = 'Important legal document dated 2025-01-15'
const fileHash = sha256(new TextEncoder().encode(document))

// 2. Create timestamp proof (you'll implement stamp() later for calendar submission)
const proof = {
  version: 1,
  fileHash,
  operations: [],
  attestations: [
    createPendingAttestation('https://alice.btc.calendar.opentimestamps.org')
  ]
}

// 3. Serialize to .ots file
const otsBytes = serializeOTS(proof)
console.log('OTS file created:', otsBytes.length, 'bytes')

// 4. Later: Deserialize and verify
const loadedProof = deserializeOTS(otsBytes)
console.log('Proof loaded:', loadedProof)

API Reference

Core Functions

serializeOTS(proof: OTSProof): Uint8Array

Convert an OTS proof object to binary .ots file format.

deserializeOTS(buffer: Uint8Array): OTSProof

Parse a binary .ots file into an OTS proof object.

applyOperations(fileHash: Uint8Array, operations: Operation[]): Uint8Array

Apply Merkle tree operations to compute final hash.

getProofInfo(proof: OTSProof): ProofInfo

Extract human-readable information from proof.

Type Definitions

interface OTSProof {
  version: number
  fileHash: Uint8Array
  operations: Operation[]
  attestations: Attestation[]
}

interface Operation {
  type: OpType
  arg?: Uint8Array
}

interface Attestation {
  type: AttestationType
  payload: Uint8Array
  uri?: string
  height?: number
}

enum OpType {
  SHA256 = 0x08,
  RIPEMD160 = 0x02,
  SHA1 = 0xf2,
  APPEND = 0xf0,
  PREPEND = 0xf1
}

enum AttestationType {
  PENDING = 0x00,
  BITCOIN = 0x05
}

Contributing

Contributions are welcome! Please feel free to open an issue or submit a pull request.

  1. Fork the repository on GitHub
  2. Clone your fork: git clone https://github.com/YOUR_USERNAME/opentimestamps.git
  3. Create a new branch: git checkout -b my-feature-branch
  4. Install dependencies: npm install
  5. Make your changes and add tests
  6. Submit a pull request with a clear description

License

This project is licensed under the MIT License. See the LICENSE file for details.


Versión en Español

En un mundo de información digital, ¿cómo puedes probar que un documento, un fragmento de código o un contrato existió en un momento específico, sin depender de un tercero centralizado y de confianza? El protocolo OpenTimestamps ofrece una solución potente y de estándar abierto al anclar pruebas criptográficas de existencia en la inmutable blockchain de Bitcoin.

@alexalves87/opentimestamps es la herramienta definitiva para que los desarrolladores de JavaScript y TypeScript aprovechen este poder. Ofrece una API limpia, moderna y basada en async/await para interactuar con el protocolo OpenTimestamps, facilitando la creación, actualización y verificación de sellos de tiempo en cualquier entorno de Node.js o navegador.

Características Principales

| Característica | Descripción | |----------------|-------------| | API Asíncrona Moderna | Construida desde cero con async/await para un código limpio, legible y sin bloqueos. | | Nativa de TypeScript | Escrita completamente en TypeScript, proporcionando un tipado fuerte y un IntelliSense superior de serie. | | Casi Cero Dependencias | Ligera y segura. Solo una dependencia criptográfica auditada (@noble/hashes), lo que reduce el tamaño de tu node_modules y la superficie de ataque. | | Compatibilidad Universal | Funciona sin problemas tanto en entornos de Node.js como en navegadores web modernos. | | Robusta y Confiable | Implementa el protocolo OpenTimestamps completo para crear, actualizar y verificar pruebas. | | Bien Documentada | Documentación exhaustiva con ejemplos claros para cada caso de uso común. | | Cobertura de Tests 100% | 136 pruebas unitarias cubriendo toda la funcionalidad crítica. |

Cómo Funciona: Conceptos Clave

El protocolo OpenTimestamps proporciona una forma con confianza minimizada de probar que unos datos existían antes de un momento determinado. El proceso se puede simplificar en tres pasos principales:

[Tus Datos] --(hash)--> [Huella Digital] --(sellar)--> [Prueba Incompleta.ots]
--(actualizar vía Servidor Calendario)--> [Prueba Completa.ots + Bloque Bitcoin]
  1. Sellar (Stamp): Proporcionas tus datos (p. ej., un documento o el búfer de un archivo). La biblioteca calcula localmente un hash criptográfico (una "huella digital" única) de estos datos, asegurando que la privacidad de tus datos se preserve. Este hash se envía a servidores públicos "Calendario". Recibes inmediatamente una prueba de sello de tiempo incompleta (un archivo .ots).

  2. Actualizar (Upgrade): Los servidores Calendario agregan tu hash con muchos otros en un Árbol de Merkle y anclan la raíz de este árbol en una única transacción de Bitcoin. Este proceso puede tardar desde unos minutos hasta unas pocas horas. Una vez confirmado en la blockchain, puedes "actualizar" tu prueba incompleta. La biblioteca contacta a los calendarios para obtener la ruta criptográfica completa desde tu hash hasta la cabecera del bloque de Bitcoin, creando una prueba completa y autocontenida.

  3. Verificar (Verify): Con la prueba completa y los datos originales, cualquiera puede verificar de forma independiente el sello de tiempo. El proceso de verificación vuelve a aplicar las operaciones criptográficas de la prueba y confirma que se vincula correctamente a un bloque válido en la blockchain de Bitcoin. Esta verificación se puede hacer sin confiar en los servidores calendario ni en ningún otro tercero, dependiendo únicamente de la seguridad matemática de Bitcoin.

Instalación

npm install @alexalves87/opentimestamps

Inicio Rápido: Tu Primer Sello de Tiempo en 60 Segundos

import { sha256 } from '@alexalves87/opentimestamps'
import { 
  serializeOTS, 
  deserializeOTS,
  createPendingAttestation 
} from '@alexalves87/opentimestamps'

// 1. Hash de tu documento
const documento = 'Documento legal importante fechado 2025-01-15'
const hashArchivo = sha256(new TextEncoder().encode(documento))

// 2. Crear prueba de timestamp (implementarás stamp() después para envío a calendarios)
const prueba = {
  version: 1,
  fileHash: hashArchivo,
  operations: [],
  attestations: [
    createPendingAttestation('https://alice.btc.calendar.opentimestamps.org')
  ]
}

// 3. Serializar a archivo .ots
const bytesOts = serializeOTS(prueba)
console.log('Archivo OTS creado:', bytesOts.length, 'bytes')

// 4. Después: Deserializar y verificar
const pruebaCargada = deserializeOTS(bytesOts)
console.log('Prueba cargada:', pruebaCargada)

Referencia de la API

Funciones Principales

serializeOTS(proof: OTSProof): Uint8Array

Convierte un objeto de prueba OTS a formato binario de archivo .ots.

deserializeOTS(buffer: Uint8Array): OTSProof

Analiza un archivo binario .ots en un objeto de prueba OTS.

applyOperations(fileHash: Uint8Array, operations: Operation[]): Uint8Array

Aplica operaciones del árbol Merkle para calcular el hash final.

getProofInfo(proof: OTSProof): ProofInfo

Extrae información legible de la prueba.

Contribuciones

¡Las contribuciones son bienvenidas! No dudes en abrir un issue o enviar un pull request.

  1. Haz un fork del repositorio en GitHub
  2. Clona tu fork: git clone https://github.com/TU_USUARIO/opentimestamps.git
  3. Crea una nueva rama: git checkout -b mi-nueva-funcionalidad
  4. Instala las dependencias: npm install
  5. Realiza tus cambios y añade pruebas
  6. Envía un pull request con una descripción clara

Licencia

Este proyecto está licenciado bajo la Licencia MIT. Consulta el archivo LICENSE para más detalles.


Made with ❤️ for the Bitcoin & TypeScript communities