How to verify a crypto webhook signature (Node.js, Python, Go)

Compute HMAC-SHA256 with your webhook secret over the string "<t>.<raw body>", compare the lowercase hex with v1 from the X-RpcNode-Signature header in constant time, reject a t that is more than five minutes from your clock, and deduplicate by X-RpcNode-Delivery. Do all of it on the raw bytes, before any JSON parsing.

What RpcNode sends

Every webhook delivery is a POST with a UTF-8 JSON body and these headers:

  • X-RpcNode-Signature: t=<unix seconds>,v1=<hex>. t is when this attempt was signed, v1 is the signature.
  • X-RpcNode-Delivery: the delivery id. It equals delivery_id in the body and stays the same on every retry, so it is your idempotency key.
  • X-RpcNode-Event: the kind (payment, payout, address, tx, payment_order, block or test).

The key is the webhook secret, webhook.secret from GET /v1/webhooks. Use the string as UTF-8 text; do not decode it from hex. This is not the request signature of the Public API itself (X-Api-Key, X-Timestamp, X-Signature), which signs your calls to us.

The algorithm

  1. Read the raw body as bytes, exactly as received.
  2. Split the header on commas, then each part on the first =. Take t and v1.
  3. Reject when t is not an integer or is more than 300 seconds from your clock.
  4. Compute HMAC-SHA256(secret, t + "." + rawBody) and hex-encode it in lowercase.
  5. Compare with v1 using a constant-time function. Never use ==.

Node.js

import crypto from 'node:crypto'
import express from 'express'

const TOLERANCE_SECONDS = 300

export function verify(rawBody, header, secret, now = Date.now() / 1000) {
  const parts = {}
  for (const item of String(header || '').split(',')) {
    const i = item.indexOf('=')
    if (i > 0) parts[item.slice(0, i).trim()] = item.slice(i + 1).trim()
  }
  if (!/^[0-9]+$/.test(parts.t || '') || !/^[0-9a-f]{64}$/.test(parts.v1 || '')) return false
  if (Math.abs(now - Number(parts.t)) > TOLERANCE_SECONDS) return false

  const expected = crypto.createHmac('sha256', secret).update(`${parts.t}.`).update(rawBody).digest()
  return crypto.timingSafeEqual(Buffer.from(parts.v1, 'hex'), expected)
}

const app = express()
// express.raw keeps the body as a Buffer. express.json() would re-serialise it and break the signature.
app.post('/rpcnode/webhook', express.raw({ type: '*/*' }), (req, res) => {
  if (!verify(req.body, req.get('X-RpcNode-Signature'), process.env.RPCNODE_WEBHOOK_SECRET)) {
    return res.sendStatus(401)
  }
  const deliveryId = req.get('X-RpcNode-Delivery')
  // ...skip if deliveryId was handled, otherwise process req.body.toString('utf8')
  res.sendStatus(200)
})

Python

import hashlib
import hmac
import re
import time

TOLERANCE_SECONDS = 300


def verify(raw_body: bytes, header: str, secret: str, now: float | None = None) -> bool:
    parts = {}
    for item in (header or "").split(","):
        key, sep, value = item.partition("=")
        if sep:
            parts[key.strip()] = value.strip()
    t, v1 = parts.get("t", ""), parts.get("v1", "")
    if not t.isdigit() or not re.fullmatch(r"[0-9a-f]{64}", v1):
        return False
    if abs((time.time() if now is None else now) - int(t)) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(secret.encode("utf-8"), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)

In Flask, call it with request.get_data() (the untouched bytes), not with request.json.

Go

package webhook

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"io"
	"math"
	"net/http"
	"strconv"
	"strings"
	"time"
)

const tolerance = 300 // seconds

func Verify(rawBody []byte, header, secret string, now time.Time) bool {
	var t, v1 string
	for _, item := range strings.Split(header, ",") {
		key, value, ok := strings.Cut(item, "=")
		if !ok {
			continue
		}
		switch strings.TrimSpace(key) {
		case "t":
			t = strings.TrimSpace(value)
		case "v1":
			v1 = strings.TrimSpace(value)
		}
	}
	seconds, err := strconv.ParseInt(t, 10, 64)
	if err != nil {
		return false
	}
	given, err := hex.DecodeString(v1)
	if err != nil || len(given) != sha256.Size {
		return false
	}
	if math.Abs(float64(now.Unix()-seconds)) > tolerance {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(t + "."))
	mac.Write(rawBody)
	return hmac.Equal(mac.Sum(nil), given)
}

func Handler(secret string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
		if err != nil || !Verify(raw, r.Header.Get("X-RpcNode-Signature"), secret, time.Now()) {
			http.Error(w, "bad signature", http.StatusUnauthorized)
			return
		}
		// dedupe by r.Header.Get("X-RpcNode-Delivery"), then process raw
		w.WriteHeader(http.StatusOK)
	}
}

Block deliveries carry the whole block as the body and can be large, so raise the body limit if you subscribe to block events.

Retries and idempotency

Any 2xx answer counts as delivered. Everything else is retried: a 4xx or 5xx status, a redirect, a connection error, or no answer within 10 seconds. The pauses are 10 s, 30 s, 2 min, 10 min, 1 h and 6 h, each varying by about 10 percent, which makes 7 attempts in roughly seven hours. After that the delivery is marked dead. Consequences for your handler:

  • Answer first, work later. Verify, answer 2xx, then process. You have 10 seconds.
  • Each attempt is signed again with a fresh t, so the five-minute window applies to every attempt, including one that arrives hours after the event.
  • A wrong 401 is expensive. If your secret or your body handling is broken, genuine deliveries are rejected and retried until they die. Answer 2xx for events you want to ignore.
  • Deduplicate. Store X-RpcNode-Delivery in the same transaction as the business effect. The same event can arrive more than once.
  • Do not rely on order. Parallel sends and retries mean arrival order is not event order. Use block_height and confirmations.

Secret rotation and testing

POST /v1/webhooks/secret issues a new secret. The old one stops working at once, including for retries that are still waiting. Deploy the new secret first, or accept both for a short time, then rotate. POST /v1/webhooks/test queues a signed test delivery (not billed); read GET /v1/webhooks/deliveries to see the HTTP status your server returned. Run it after every change of URL or secret.

Limits and caveats

  • The signature proves the body came from someone holding your secret and was not altered. It does not prove the payment is genuine for your order: also match order_id, payment_id and the amount.
  • The egress IP list in GET /v1/webhooks is useful for firewalls, but the docs advise not to rely on IPs alone.
  • The official SDKs include a helper that checks this header, so you may not need your own code.

Related: accept USDT TRC-20 payments, the Webhooks reference, the Payments product and pricing.