> For the complete documentation index, see [llms.txt](https://docs.metasleuth.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.metasleuth.io/blocksec-aml-api/introduction/request-signing.md).

# Request Signing

Request Signing adds verification to your API requests using an API secret. Your API key identifies your API access; your secret generates a signature and must never be sent in requests.

Address Label API and Risk Score API use separate API keys and secrets. Use the credentials for the service you are calling.

## Enable Request Signing

For the complete configuration, rotation and disable workflows, see [API Security Settings](https://docs.metasleuth.io/blocksec-aml-api/introduction/api-security-settings.md).

1. Open [Settings → APIs → API Keys](https://metasleuth.io/system/settings/personal/apis), then open **Security Settings** for the appropriate API.
2. Select **Request Signing** and generate an API secret. Copy and store it securely: it is shown only once.
3. Choose when signed requests become required, then select **Save Changes**:
   * **In 24 hours**: use the transition period to update and test your applications. The new secret works after saving; requests without signatures remain accepted until the displayed enforcement time, subject to other access rules.
   * **Immediately**: every request must include a valid signature after saving. Make sure your applications are ready.
4. Send signed requests using the instructions below. Update all applications before the enforcement time displayed in Security Settings.

An invalid signature is rejected even during the transition period. If IP Allowlist is also enabled, the source IP must be allowed and the signature must be valid. Testing uses real business API requests and may consume API quota; there is no separate test secret or signature-validation endpoint.

## Request headers

| Header        | Value                                                                    |
| ------------- | ------------------------------------------------------------------------ |
| `Api-Key`     | API key for the service                                                  |
| `X-Timestamp` | Current Unix timestamp in seconds                                        |
| `X-Nonce`     | A fresh, random, unique value for each request, no longer than 256 bytes |
| `X-Signature` | `v1=` followed by the lowercase hexadecimal HMAC-SHA256 signature        |

The timestamp must be within **5 minutes** of server time. Keep your system clock synchronized. Generate a new timestamp, nonce and signature for every retry.

Keep both your API key and secret in server-side code only. Load them from environment variables or a secret manager; never commit them or include them in browser or mobile application bundles.

Use HTTPS with certificate verification enabled. Request Signing authenticates requests; it does not encrypt their contents. Do not put credentials in URLs or query parameters. Redact API keys, secrets, signature headers and sensitive request/response data from logs, traces, screenshots and support attachments.

## Construct the canonical string

Join the following six fields with a single newline (`\n`). Do not add a trailing newline.

```
METHOD
PATH
SORTED_QUERY_STRING
BODY_SHA256
TIMESTAMP
NONCE
```

* **METHOD**: uppercase HTTP method, such as `GET` or `POST`.
* **PATH**: full URL path, including the service prefix, excluding the scheme, host and query string. For example, `/address-compliance/api/v3/risk-score`. Using only `/risk-score` will fail verification.
* **SORTED\_QUERY\_STRING**: normalized query string as described below. Use an empty string if there are no query parameters.
* **BODY\_SHA256**: lowercase hexadecimal SHA-256 hash of the exact bytes sent as the request body. For an empty body, hash an empty byte string.
* **TIMESTAMP** and **NONCE**: the same values sent in the request headers.

Serialize your request body once, hash those bytes, then send exactly those bytes. Changing JSON whitespace after signing invalidates the signature.

### Normalize query parameters

1. Split the raw query string on `&`, then split each pair on the first `=`. Treat a missing value as an empty string.
2. Decode the keys and values.
3. Sort by decoded key, then decoded value, using UTF-8 byte order. Preserve duplicate keys.
4. Encode each key and value using RFC 3986 percent encoding. Leave only `A–Z`, `a–z`, `0–9`, `-`, `_`, `.`, and `~` unescaped. Encode spaces as `%20` and literal plus signs as `%2B`.
5. Join each `key=value` pair with `&`, without a leading `?`.

Example:

```
Raw:        b=2&a=1&a=%20&c=x%3Dy
Normalized: a=%20&a=1&b=2&c=x%3Dy
```

Use UTF-8. Avoid raw `+` in query values; use `%20` for spaces and `%2B` for a literal plus sign. `flag` and `flag=` both normalize to `flag=`.

### Calculate the signature

```
X-Signature = "v1=" + hex_lowercase(
    HMAC-SHA256(secret_utf8_bytes, canonical_string_utf8_bytes)
)
```

Use the secret as the UTF-8 bytes of the displayed value. Do not hex-decode or Base64-decode it.

## Python example

This example calls the Risk Score API's supported-chain endpoint. Set `MS_API_KEY` and `MS_API_SECRET` to your Risk Score credentials. The example uses the production HTTPS endpoint. Use separate credentials for any authorized test environment; never send production credentials to an untrusted host.

```python
import hashlib
import hmac
import os
import time
import uuid
from urllib.parse import parse_qsl, quote, urlencode, urlsplit
from urllib.error import HTTPError
from urllib.request import HTTPRedirectHandler, Request, build_opener


def normalize_query(raw_query):
    pairs = parse_qsl(raw_query, keep_blank_values=True,
                      encoding="utf-8", errors="strict")
    pairs.sort(key=lambda p: (p[0].encode("utf-8"), p[1].encode("utf-8")))
    return urlencode(pairs, quote_via=quote, safe="-_.~")


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise HTTPError(req.full_url, code, "Redirect refused", headers, fp)


base = "https://aml.blocksec.com/address-compliance/api/v3"
url = base + "/chain-list"
method = "GET"
body = b""
parts = urlsplit(url)
timestamp = str(int(time.time()))
nonce = uuid.uuid4().hex
canonical = "\n".join([
    method,
    parts.path,
    normalize_query(parts.query),
    hashlib.sha256(body).hexdigest(),
    timestamp,
    nonce,
])
signature = "v1=" + hmac.new(
    os.environ["MS_API_SECRET"].encode("utf-8"),
    canonical.encode("utf-8"),
    hashlib.sha256,
).hexdigest()
request = Request(url, method=method, headers={
    "Api-Key": os.environ["MS_API_KEY"],
    "X-Timestamp": timestamp,
    "X-Nonce": nonce,
    "X-Signature": signature,
})
with build_opener(NoRedirect()).open(request, timeout=20) as response:
    print("HTTP status:", response.status)
    # Process response.read() in your application; avoid logging sensitive data.
```

For a JSON POST request, serialize the payload into UTF-8 bytes, use those bytes for the body hash, then pass the same bytes as `data=body` to `Request`. Set `Content-Type: application/json`.

See [APIs](https://docs.metasleuth.io/blocksec-aml-api/wallet-screening-api/apis.md) for request parameters.

## Node.js example

Requires Node.js 18 or later. Use the same Risk Score environment variables as the Python example. The example signs the exact UTF-8 bytes that it sends.

```javascript
import { createHash, createHmac, randomUUID } from 'node:crypto';

function encode(value) {
  return encodeURIComponent(value).replace(/[!'()*]/g, ch =>
    '%' + ch.charCodeAt(0).toString(16).toUpperCase());
}
function normalizeQuery(raw) {
  const pairs = [...new URLSearchParams(raw).entries()];
  pairs.sort((a, b) => Buffer.compare(Buffer.from(a[0]), Buffer.from(b[0]))
    || Buffer.compare(Buffer.from(a[1]), Buffer.from(b[1])));
  return pairs.map(([k, v]) => `${encode(k)}=${encode(v)}`).join('&');
}
const key = process.env.MS_API_KEY;
const secret = process.env.MS_API_SECRET;
if (!key || !secret) throw new Error('Set MS_API_KEY and MS_API_SECRET');
const base = 'https://aml.blocksec.com/address-compliance/api/v3';
const url = new URL(base + '/risk-score');
const method = 'POST';
const body = Buffer.from(JSON.stringify({
  chain_id: 1,
  address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
  interaction_risk: false,
}), 'utf8');
const timestamp = Math.floor(Date.now() / 1000).toString();
const nonce = randomUUID();
const canonical = [method, url.pathname, normalizeQuery(url.search.slice(1)),
  createHash('sha256').update(body).digest('hex'), timestamp, nonce].join('\n');
const signature = 'v1=' + createHmac('sha256', Buffer.from(secret, 'utf8'))
  .update(canonical, 'utf8').digest('hex');
const response = await fetch(url, {
  method,
  headers: {
    'Content-Type': 'application/json',
    'Api-Key': key,
    'X-Timestamp': timestamp,
    'X-Nonce': nonce,
    'X-Signature': signature,
  },
  body,
  redirect: 'error',
});
console.log('HTTP status:', response.status);
// Process await response.json() in your application; avoid logging sensitive data.
```

## Java example

Requires Java 11 or later; no external dependencies. Save as `RequestSigning.java`, set `MS_API_KEY` and `MS_API_SECRET` to your Address Label credentials, then run `java RequestSigning.java`. This calls the production Address Label supported-chain endpoint. Use the matching service credentials; Risk Score credentials cannot be substituted.

```java
import java.net.URI;
import java.net.URLDecoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/** Java 11+, no external dependencies. */
public class RequestSigning {
    static byte[] utf8(String value) { return value.getBytes(StandardCharsets.UTF_8); }

    static String hex(byte[] bytes) {
        StringBuilder out = new StringBuilder();
        for (byte b : bytes) out.append(String.format("%02x", b & 255));
        return out.toString();
    }

    static String encode(String value) {
        StringBuilder out = new StringBuilder();
        String digits = "0123456789ABCDEF";
        for (byte b : utf8(value)) {
            int c = b & 255;
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
                    || (c >= '0' && c <= '9') || c == '-' || c == '_'
                    || c == '.' || c == '~') out.append((char) c);
            else out.append('%').append(digits.charAt(c >> 4)).append(digits.charAt(c & 15));
        }
        return out.toString();
    }

    static String normalizeQuery(String raw) {
        if (raw == null || raw.isEmpty()) return "";
        List<String[]> pairs = new ArrayList<>();
        for (String part : raw.split("&")) {
            if (part.isEmpty()) continue;
            String[] pair = part.split("=", 2);
            pairs.add(new String[] {URLDecoder.decode(pair[0], StandardCharsets.UTF_8),
                URLDecoder.decode(pair.length == 2 ? pair[1] : "", StandardCharsets.UTF_8)});
        }
        pairs.sort((a, b) -> {
            int order = Arrays.compareUnsigned(utf8(a[0]), utf8(b[0]));
            return order != 0 ? order : Arrays.compareUnsigned(utf8(a[1]), utf8(b[1]));
        });
        List<String> encoded = new ArrayList<>();
        for (String[] pair : pairs) encoded.add(encode(pair[0]) + "=" + encode(pair[1]));
        return String.join("&", encoded);
    }

    static String canonical(String method, URI uri, byte[] body, String timestamp,
                            String nonce) throws Exception {
        return String.join("\n", method.toUpperCase(Locale.ROOT), uri.getRawPath(),
            normalizeQuery(uri.getRawQuery()),
            hex(MessageDigest.getInstance("SHA-256").digest(body)), timestamp, nonce);
    }

    static String sign(String secret, String canonical) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(utf8(secret), "HmacSHA256"));
        return "v1=" + hex(mac.doFinal(utf8(canonical)));
    }

    static String requiredEnv(String name) {
        String value = System.getenv(name);
        if (value == null || value.isEmpty()) throw new IllegalArgumentException("Set " + name);
        return value;
    }

    public static void main(String[] args) throws Exception {
        String key = requiredEnv("MS_API_KEY");
        String secret = requiredEnv("MS_API_SECRET");
        URI uri = URI.create("https://aml.blocksec.com/address-label/api/v3/chain-list");
        String method = "GET";
        byte[] body = new byte[0];
        String timestamp = Long.toString(Instant.now().getEpochSecond());
        String nonce = UUID.randomUUID().toString();
        String signature = sign(secret, canonical(method, uri, body, timestamp, nonce));
        HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(20))
            .header("Api-Key", key).header("X-Timestamp", timestamp)
            .header("X-Nonce", nonce).header("X-Signature", signature)
            .method(method, HttpRequest.BodyPublishers.ofByteArray(body)).build();
        HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(20))
            .followRedirects(HttpClient.Redirect.NEVER).build();
        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        System.out.println("HTTP status: " + response.statusCode());
        // Process response.body() and check the business code; do not log sensitive data.
    }
}
```

For JSON POST requests, serialize once into a UTF-8 `byte[]`, use it as `body`, set `method` to `POST`, update the full endpoint URI and add `Content-Type: application/json`. The same bytes must be hashed and sent. Use Unix seconds, UTF-8 secret bytes without decoding, and unsigned UTF-8 byte ordering for query parameters; Java's default string ordering is not equivalent for all Unicode characters.

All examples refuse redirects. Do not forward credentials or signature headers to a redirected destination. Verify the intended HTTPS host and path before constructing and signing a new request. An HTTP status alone does not establish business success; check the JSON business code as described in [Response Format](https://docs.metasleuth.io/blocksec-aml-api/introduction/response-format.md).

## Troubleshooting

| Code     | Message                                     | What to check                                                                                                                              |
| -------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `401001` | Request signing is not configured           | Configure signing and confirm an available secret exists for this API service.                                                             |
| `401002` | Invalid request signature                   | Correct service credentials, complete headers, full path, method, normalized query, exact body bytes and nonce length (at most 256 bytes). |
| `401003` | Invalid request timestamp                   | Use Unix seconds and synchronize your clock; the timestamp must be within 5 minutes of server time.                                        |
| `401004` | Request has already been used               | Generate a fresh nonce and signature for each retry.                                                                                       |
| `403002` | Request IP is not allowed                   | Check your application's public outbound IP against the enabled allowlist.                                                                 |
| `500003` | Request signing verification is unavailable | Retry with bounded backoff and a new nonce/signature. Contact support if it persists.                                                      |

See [Response Format](https://docs.metasleuth.io/blocksec-aml-api/introduction/response-format.md) for the full list and HTTP handling.

A successful retry can be charged again: nonces prevent replay, not duplicate billing. Sending any non-empty signature header triggers verification even when signing is not enabled.

## Rotate your secret

Generate a new secret in Security Settings, copy it securely, and choose when the old secret expires. Select **Save Changes** to apply the rotation; generating an unsaved secret does not replace your current secret.

* **In 24 hours**: after saving, both secrets work during the transition. Update all applications before the old secret expires.
* **Immediately**: after saving, the old secret stops working. Use this option if you suspect the old secret has been exposed.

Your API key stays unchanged. A new rotation cannot start while another is in progress. Wait for the old secret to expire, or revoke it early before rotating again. Revoking it early immediately rejects requests signed with that secret.
