375 lines
13 KiB
Go
375 lines
13 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.intruders.space/public/opentimestamps"
|
|
"git.intruders.space/public/opentimestamps/ots"
|
|
"git.intruders.space/public/opentimestamps/verifyer"
|
|
"github.com/jung-kurt/gofpdf"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var (
|
|
// PDF command flags
|
|
pdfOutput string
|
|
pdfIncludeContent bool
|
|
pdfTitle string
|
|
pdfComment string
|
|
pdfEsploraURL string
|
|
)
|
|
|
|
// pdfCmd represents the pdf command
|
|
var pdfCmd = &cobra.Command{
|
|
Use: "pdf [flags] <file> <file.ots>",
|
|
Short: "Generate a PDF certificate for a timestamp",
|
|
Long: `Generate a PDF certificate that explains how to verify the timestamp.
|
|
The PDF includes all necessary information such as hashes, operations,
|
|
and instructions for manual verification.`,
|
|
Args: cobra.ExactArgs(2),
|
|
Run: runPdfCmd,
|
|
}
|
|
|
|
func init() {
|
|
// Local flags for the pdf command
|
|
pdfCmd.Flags().StringVarP(&pdfOutput, "output", "o", "", "Output PDF filename (default: original filename with .pdf extension)")
|
|
pdfCmd.Flags().BoolVar(&pdfIncludeContent, "include-content", false, "Include the original file content in the PDF (for text files only)")
|
|
pdfCmd.Flags().StringVar(&pdfTitle, "title", "OpenTimestamps Certificate", "Title for the PDF document")
|
|
pdfCmd.Flags().StringVar(&pdfComment, "comment", "", "Additional comment to include in the certificate")
|
|
pdfCmd.Flags().StringVar(&pdfEsploraURL, "esplora", "https://blockstream.info/api", "URL of Esplora API for fetching block information")
|
|
}
|
|
|
|
func runPdfCmd(cmd *cobra.Command, args []string) {
|
|
filePath := args[0]
|
|
otsPath := args[1]
|
|
|
|
// Determine output file path
|
|
outputPath := pdfOutput
|
|
if outputPath == "" {
|
|
outputPath = filePath + ".certificate.pdf"
|
|
}
|
|
|
|
// Read the original file
|
|
fileData, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
slog.Error("Failed to read file", "file", filePath, "error", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Compute the file digest
|
|
fileDigest := sha256.Sum256(fileData)
|
|
slog.Debug("Computed file digest", "digest", hex.EncodeToString(fileDigest[:]))
|
|
|
|
// Read and parse the OTS file
|
|
otsData, err := os.ReadFile(otsPath)
|
|
if err != nil {
|
|
slog.Error("Failed to read OTS file", "file", otsPath, "error", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
timestampFile, err := opentimestamps.ReadFromFile(otsData)
|
|
if err != nil {
|
|
slog.Error("Failed to parse OTS file", "file", otsPath, "error", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Check if the digests match
|
|
if !bytes.Equal(fileDigest[:], timestampFile.Digest) {
|
|
slog.Warn("Warning: File digest doesn't match timestamp digest",
|
|
"file_digest", hex.EncodeToString(fileDigest[:]),
|
|
"timestamp_digest", hex.EncodeToString(timestampFile.Digest))
|
|
}
|
|
|
|
// Extract Bitcoin attestations
|
|
bitcoinSeqs := timestampFile.GetBitcoinAttestedSequences()
|
|
if len(bitcoinSeqs) == 0 {
|
|
slog.Warn("No Bitcoin attestations found in timestamp, certificate will be for pending timestamps")
|
|
}
|
|
|
|
// Create Bitcoin interface for block time lookup
|
|
bitcoin := verifyer.NewEsploraClient(pdfEsploraURL, 30*time.Second)
|
|
slog.Info("Using Esplora API for block information", "url", pdfEsploraURL)
|
|
|
|
// Generate the PDF
|
|
err = generateVerificationPDF(
|
|
outputPath,
|
|
filePath,
|
|
fileData,
|
|
fileDigest[:],
|
|
timestampFile,
|
|
bitcoinSeqs,
|
|
bitcoin,
|
|
)
|
|
if err != nil {
|
|
slog.Error("Failed to generate PDF", "error", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
slog.Info("PDF certificate generated successfully", "file", outputPath)
|
|
}
|
|
|
|
func generateVerificationPDF(outputPath, filePath string, fileData []byte, fileDigest []byte,
|
|
timestamp *ots.File, bitcoinSeqs []ots.Sequence, bitcoin verifyer.Bitcoin) error {
|
|
|
|
// Create a new PDF
|
|
pdf := gofpdf.New("P", "mm", "A4", "")
|
|
pdf.SetTitle(pdfTitle, true)
|
|
pdf.SetAuthor("OpenTimestamps", true)
|
|
pdf.SetCreator("OpenTimestamps CLI", true)
|
|
|
|
// Set margins
|
|
pdf.SetMargins(25, 25, 25)
|
|
pdf.SetAutoPageBreak(true, 25)
|
|
|
|
// Add first page - Certificate
|
|
pdf.AddPage()
|
|
|
|
// Title
|
|
pdf.SetFont("Helvetica", "B", 24)
|
|
pdf.CellFormat(0, 12, pdfTitle, "", 1, "C", false, 0, "")
|
|
pdf.Ln(10)
|
|
|
|
// Timestamp information section
|
|
pdf.SetFont("Helvetica", "B", 18)
|
|
pdf.CellFormat(0, 10, "Timestamp Information", "", 1, "L", false, 0, "")
|
|
pdf.Ln(5)
|
|
|
|
pdf.SetFont("Helvetica", "B", 12)
|
|
pdf.CellFormat(0, 8, "Filename:", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Helvetica", "", 12)
|
|
pdf.CellFormat(0, 8, filepath.Base(filePath), "", 1, "L", false, 0, "")
|
|
pdf.Ln(2)
|
|
|
|
// Timestamp date
|
|
pdf.SetFont("Helvetica", "B", 12)
|
|
if len(bitcoinSeqs) > 0 {
|
|
// Find the earliest Bitcoin attestation
|
|
var earliestHeight uint64
|
|
var earliestBlockTime time.Time
|
|
|
|
for _, seq := range bitcoinSeqs {
|
|
att := seq.GetAttestation()
|
|
if earliestHeight == 0 || att.BitcoinBlockHeight < earliestHeight {
|
|
earliestHeight = att.BitcoinBlockHeight
|
|
|
|
// Fetch the block time from the blockchain
|
|
blockHash, err := bitcoin.GetBlockHash(int64(att.BitcoinBlockHeight))
|
|
if err == nil {
|
|
blockHeader, err := bitcoin.GetBlockHeader(blockHash)
|
|
if err == nil {
|
|
earliestBlockTime = time.Unix(int64(blockHeader.Timestamp.Unix()), 0)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Show Bitcoin timestamp
|
|
pdf.CellFormat(0, 8, "Timestamp Created:", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Helvetica", "", 12)
|
|
|
|
if !earliestBlockTime.IsZero() {
|
|
// If we successfully retrieved the block time, display it
|
|
pdf.CellFormat(0, 8, fmt.Sprintf("Bitcoin Block #%d (%s)",
|
|
earliestHeight, earliestBlockTime.Format("Jan 02, 2006 15:04:05 UTC")),
|
|
"", 1, "L", false, 0, "")
|
|
} else {
|
|
// Fallback to just showing the block height
|
|
pdf.CellFormat(0, 8, fmt.Sprintf("Bitcoin Block #%d", earliestHeight), "", 1, "L", false, 0, "")
|
|
}
|
|
} else {
|
|
// Pending attestation
|
|
pdf.CellFormat(0, 8, "Status:", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Helvetica", "", 12)
|
|
pdf.CellFormat(0, 8, "Pending confirmation in the Bitcoin blockchain", "", 1, "L", false, 0, "")
|
|
}
|
|
pdf.Ln(2)
|
|
|
|
// File hash
|
|
pdf.SetFont("Helvetica", "B", 12)
|
|
pdf.CellFormat(0, 8, "File SHA-256 Digest:", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Courier", "", 10)
|
|
pdf.CellFormat(0, 8, hex.EncodeToString(fileDigest), "", 1, "L", false, 0, "")
|
|
pdf.Ln(5)
|
|
|
|
// Include comment if provided
|
|
if pdfComment != "" {
|
|
pdf.SetFont("Helvetica", "B", 12)
|
|
pdf.CellFormat(0, 8, "Comment:", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Helvetica", "", 12)
|
|
pdf.MultiCell(0, 8, pdfComment, "", "L", false)
|
|
pdf.Ln(5)
|
|
}
|
|
|
|
// Include file content if requested and looks like text
|
|
if pdfIncludeContent && isTextFile(fileData) && len(fileData) < 5000 {
|
|
pdf.SetFont("Helvetica", "B", 12)
|
|
pdf.CellFormat(0, 8, "File Content:", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Courier", "", 10)
|
|
content := string(fileData)
|
|
content = strings.ReplaceAll(content, "\r\n", "\n")
|
|
pdf.MultiCell(0, 5, content, "", "L", false)
|
|
pdf.Ln(5)
|
|
}
|
|
|
|
// Add Bitcoin transaction information for each attestation
|
|
if len(bitcoinSeqs) > 0 {
|
|
pdf.SetFont("Helvetica", "B", 18)
|
|
pdf.CellFormat(0, 10, "Bitcoin Attestations", "", 1, "L", false, 0, "")
|
|
pdf.Ln(5)
|
|
|
|
for i, seq := range bitcoinSeqs {
|
|
att := seq.GetAttestation()
|
|
|
|
pdf.SetFont("Helvetica", "B", 14)
|
|
pdf.CellFormat(0, 8, fmt.Sprintf("Attestation #%d", i+1), "", 1, "L", false, 0, "")
|
|
pdf.Ln(2)
|
|
|
|
// Get block details
|
|
blockHash, err := bitcoin.GetBlockHash(int64(att.BitcoinBlockHeight))
|
|
blockTime := "Unknown"
|
|
if err == nil {
|
|
blockHeader, err := bitcoin.GetBlockHeader(blockHash)
|
|
if err == nil {
|
|
blockTime = blockHeader.Timestamp.Format("Jan 02, 2006 15:04:05 UTC")
|
|
}
|
|
}
|
|
|
|
pdf.SetFont("Helvetica", "B", 12)
|
|
pdf.CellFormat(0, 8, "Bitcoin Block Height:", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Helvetica", "", 12)
|
|
pdf.CellFormat(0, 8, fmt.Sprintf("%d", att.BitcoinBlockHeight), "", 1, "L", false, 0, "")
|
|
|
|
pdf.SetFont("Helvetica", "B", 12)
|
|
pdf.CellFormat(0, 8, "Block Time:", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Helvetica", "", 12)
|
|
pdf.CellFormat(0, 8, blockTime, "", 1, "L", false, 0, "")
|
|
|
|
pdf.SetFont("Helvetica", "B", 12)
|
|
pdf.CellFormat(0, 8, "Block Hash:", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Courier", "", 10)
|
|
if blockHash != nil {
|
|
pdf.CellFormat(0, 8, blockHash.String(), "", 1, "L", false, 0, "")
|
|
} else {
|
|
pdf.CellFormat(0, 8, "Unable to retrieve", "", 1, "L", false, 0, "")
|
|
}
|
|
|
|
// In a full implementation, we would show the Bitcoin merkle root and transaction ID
|
|
// This would require additional API calls to get that information
|
|
|
|
// Show operations sequence
|
|
pdf.SetFont("Helvetica", "B", 12)
|
|
pdf.CellFormat(0, 8, "Verification Operations:", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Courier", "", 10)
|
|
|
|
// Format the operations
|
|
var operationsText string
|
|
merkleRoot, _ := seq.Compute(timestamp.Digest)
|
|
|
|
operationsText += fmt.Sprintf("Starting with digest: %s\n", hex.EncodeToString(timestamp.Digest))
|
|
|
|
for j, inst := range seq {
|
|
if inst.Operation != nil {
|
|
if inst.Operation.Binary {
|
|
operationsText += fmt.Sprintf("%d. %s %s\n", j+1, inst.Operation.Name, hex.EncodeToString(inst.Argument))
|
|
} else {
|
|
operationsText += fmt.Sprintf("%d. %s\n", j+1, inst.Operation.Name)
|
|
}
|
|
}
|
|
}
|
|
|
|
operationsText += fmt.Sprintf("\nResulting merkle root: %s\n", hex.EncodeToString(merkleRoot))
|
|
|
|
pdf.MultiCell(0, 5, operationsText, "", "L", false)
|
|
pdf.Ln(5)
|
|
}
|
|
}
|
|
|
|
// Add second page - Verification Instructions
|
|
pdf.AddPage()
|
|
pdf.SetFont("Helvetica", "B", 18)
|
|
pdf.CellFormat(0, 10, "Verification Instructions", "", 1, "L", false, 0, "")
|
|
pdf.Ln(5)
|
|
|
|
// Instructions
|
|
addVerificationInstructions(pdf)
|
|
|
|
// Save the PDF
|
|
return pdf.OutputFileAndClose(outputPath)
|
|
}
|
|
|
|
func addVerificationInstructions(pdf *gofpdf.Fpdf) {
|
|
pdf.SetFont("Helvetica", "B", 14)
|
|
pdf.CellFormat(0, 8, "1. Compute the SHA-256 digest of your file", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Helvetica", "", 12)
|
|
pdf.MultiCell(0, 6, `To verify this timestamp, first compute the SHA-256 digest of your original file. You can use various tools for this:
|
|
|
|
- On Linux/macOS: Use the command "shasum -a 256 filename"
|
|
- On Windows: Use tools like PowerShell's "Get-FileHash" or third-party tools
|
|
- Online: Various websites can calculate file hashes, but only use trusted sources for sensitive files
|
|
|
|
Verify that the digest matches the one shown in this certificate.`, "", "L", false)
|
|
pdf.Ln(5)
|
|
|
|
pdf.SetFont("Helvetica", "B", 14)
|
|
pdf.CellFormat(0, 8, "2. Verify the operations sequence", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Helvetica", "", 12)
|
|
pdf.MultiCell(0, 6, `The operations sequence shown in this certificate transforms the file digest into a value that was stored in the Bitcoin blockchain. To verify manually:
|
|
|
|
- Start with the file's SHA-256 digest
|
|
- Apply each operation in sequence as shown in the certificate
|
|
- For "append" operations, add the shown bytes to the end of the current value
|
|
- For "prepend" operations, add the shown bytes to the beginning of the current value
|
|
- For "sha256" operations, compute the SHA-256 hash of the current value
|
|
- The final result should match the merkle root shown in the certificate`, "", "L", false)
|
|
pdf.Ln(5)
|
|
|
|
pdf.SetFont("Helvetica", "B", 14)
|
|
pdf.CellFormat(0, 8, "3. Verify the Bitcoin attestation", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Helvetica", "", 12)
|
|
pdf.MultiCell(0, 6, `For full verification, check that the merkle root was recorded in the Bitcoin blockchain:
|
|
|
|
- Find the Bitcoin block at the height shown in the certificate
|
|
- The block's merkle root or transaction should contain the computed value
|
|
- You can use block explorers like blockstream.info or blockchain.com
|
|
- The timestamp is confirmed when the merkle root appears in the blockchain`, "", "L", false)
|
|
pdf.Ln(5)
|
|
|
|
pdf.SetFont("Helvetica", "B", 14)
|
|
pdf.CellFormat(0, 8, "4. Use the OpenTimestamps verifier", "", 1, "L", false, 0, "")
|
|
pdf.SetFont("Helvetica", "", 12)
|
|
pdf.MultiCell(0, 6, `For easier verification, use the OpenTimestamps verification tools:
|
|
|
|
- Command line: Use "ots verify <file> <file.ots>"
|
|
- Online: Visit https://opentimestamps.org and upload your file and .ots timestamp
|
|
- The tools will perform all verification steps automatically`, "", "L", false)
|
|
|
|
// Add footer with generation time
|
|
pdf.Ln(10)
|
|
pdf.SetFont("Helvetica", "I", 10)
|
|
pdf.CellFormat(0, 6, fmt.Sprintf("Certificate generated at: %s", time.Now().Format(time.RFC3339)), "", 1, "C", false, 0, "")
|
|
pdf.CellFormat(0, 6, "OpenTimestamps - https://opentimestamps.org", "", 1, "C", false, 0, "")
|
|
}
|
|
|
|
// isTextFile tries to determine if a file is likely to be text
|
|
func isTextFile(data []byte) bool {
|
|
// Simple heuristic: if the file doesn't contain too many non-printable characters,
|
|
// it's probably text
|
|
nonPrintable := 0
|
|
for _, b := range data {
|
|
if (b < 32 || b > 126) && b != 9 && b != 10 && b != 13 {
|
|
nonPrintable++
|
|
}
|
|
}
|
|
|
|
// Allow up to 1% non-printable characters
|
|
return nonPrintable <= len(data)/100
|
|
}
|