> For the complete documentation index, see [llms.txt](https://docs.luganodes.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.luganodes.com/tron-energy/energy-rental-api/making-requests.md).

# Authentication and signing

Sign every request with HMAC-SHA256: the headers, the string to sign and working code.

Every Energy Rental API request carries your API key, a timestamp and a signature made with your secret. The base URL, formats and rate limits are on [Conventions and limits](https://docs.luganodes.com/tron-energy/energy-rental-api/conventions-and-limits.md).

## Headers

Send all three headers on every request, including `GET` requests.

| Header        | Value                                                                |
| ------------- | -------------------------------------------------------------------- |
| `X-API-Key`   | Your API key                                                         |
| `X-Timestamp` | Current Unix time in seconds. Must be within 30 seconds of our clock |
| `X-Signature` | HMAC-SHA256 signature of the request, as lowercase hex               |

A request with a body also sends `Content-Type: application/json`.

A timestamp outside the 30-second tolerance fails with `401 UNAUTHORIZED`. Keep your servers on network time (NTP) and read the clock when you sign each request, not once at start-up.

## String to sign

The signature covers four elements, joined by single newline characters.

```
STRING_TO_SIGN = METHOD + "\n" + PATH + "\n" + TIMESTAMP + "\n" + BODY
SIGNATURE      = lowercase_hex(HMAC_SHA256(key = API_SECRET, message = STRING_TO_SIGN))
```

| Element     | What it is                                                       | Rules                                                                                                                                 |
| ----------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `METHOD`    | The HTTP method                                                  | Upper case, for example `GET` or `POST`                                                                                               |
| `PATH`      | The request path with its query string, relative to the base URL | Starts with `/v1/`. Include the `?` and the query string exactly as you send it, in the same order. Leave out the scheme and the host |
| `TIMESTAMP` | The value of the `X-Timestamp` header                            | Unix time in whole seconds, digits only                                                                                               |
| `BODY`      | The request body                                                 | The exact bytes you send. Empty for `GET`                                                                                             |
| `\n`        | The separator                                                    | One line feed character (byte 0x0A). No carriage return                                                                               |

The string ends with `BODY` and nothing else. For a `GET` request `BODY` is empty, so the string ends with the newline that follows `TIMESTAMP`. Two examples, with `\n` standing for the newline. Sample IDs, addresses and hashes are illustrative.

```
GET\n/v1/rentals?status=reclaimed&limit=50\n1793145600\n
POST\n/v1/estimate\n1793145600\n{"from":"TJdhGqPPUGMhLWxZdMU87f7muvoN14LPpg","to":"TDyfoQmyKQoimRXgKfGsK94JBpZh2aVe3Y","token":"USDT","amount":"10000000"}
```

## Generate the signature

1. Serialise the JSON body once. Use an empty string for a `GET`.
2. Read the clock in whole seconds. This is `TIMESTAMP` and the `X-Timestamp` value.
3. Join `METHOD`, `PATH`, `TIMESTAMP` and `BODY` with `\n`.
4. Compute the HMAC-SHA256 of that string with your secret and encode it as lowercase hex. This is the `X-Signature` value.
5. Send the three headers and the body from step 1, unchanged.

Sign what you send. A client that re-serialises the body, with different spacing or key order, sends different bytes and the signature no longer matches. Sign each retry again with a new timestamp.

## Signing helpers

The helpers sign a request and send it. The Node.js and Python helpers return the HTTP status and the parsed response; `signed_curl` in `tron_energy.sh` prints the response body. They read `BASE_URL`, `API_KEY` and `API_SECRET` from the environment, and the path you pass includes the query string. Other pages in this section call them.

{% tabs %}
{% tab title="cURL" %}
Export `BASE_URL`, `API_KEY` and `API_SECRET`, then compute the signature inline with `openssl`. The variable is `REQUEST_PATH` because `PATH` is the shell's own variable.

A `POST` with a body:

{% code title="sign-post.sh" %}

```bash
TIMESTAMP=$(date +%s)
REQUEST_PATH="/v1/estimate"
BODY='{"from":"TJdhGqPPUGMhLWxZdMU87f7muvoN14LPpg","to":"TDyfoQmyKQoimRXgKfGsK94JBpZh2aVe3Y","token":"USDT","amount":"10000000"}'
SIGNATURE=$(printf '%s\n%s\n%s\n%s' "POST" "$REQUEST_PATH" "$TIMESTAMP" "$BODY" | openssl dgst -sha256 -hmac "$API_SECRET" | sed 's/^.* //')
curl -X POST "$BASE_URL$REQUEST_PATH" \
  -H "X-API-Key: $API_KEY" \
  -H "X-Timestamp: $TIMESTAMP" \
  -H "X-Signature: $SIGNATURE" \
  -H "Content-Type: application/json" \
  -d "$BODY"
```

{% endcode %}

A `GET` has an empty body and no `Content-Type`. The query string is part of the signed path:

{% code title="sign-get.sh" %}

```bash
TIMESTAMP=$(date +%s)
REQUEST_PATH="/v1/rentals?status=reclaimed&limit=50"
BODY=""
SIGNATURE=$(printf '%s\n%s\n%s\n%s' "GET" "$REQUEST_PATH" "$TIMESTAMP" "$BODY" | openssl dgst -sha256 -hmac "$API_SECRET" | sed 's/^.* //')
curl -X GET "$BASE_URL$REQUEST_PATH" \
  -H "X-API-Key: $API_KEY" \
  -H "X-Timestamp: $TIMESTAMP" \
  -H "X-Signature: $SIGNATURE"
```

{% endcode %}

To sign each call with one command, save this function as `tron_energy.sh` and load it into your shell with `source tron_energy.sh`. The Quickstart's cURL steps call it.

{% code title="tron\_energy.sh" %}

```bash
# Usage: signed_curl METHOD PATH [BODY]
signed_curl() {
  local req_method="$1" req_path="$2" req_body="${3-}" ts sig
  ts=$(date +%s)
  sig=$(printf '%s\n%s\n%s\n%s' "$req_method" "$req_path" "$ts" "$req_body" \
    | openssl dgst -sha256 -hmac "$API_SECRET" | sed 's/^.* //')
  set -- -sS -X "$req_method" "$BASE_URL$req_path" \
    -H "X-API-Key: $API_KEY" -H "X-Timestamp: $ts" -H "X-Signature: $sig"
  if [ -n "$req_body" ]; then
    set -- "$@" -H "Content-Type: application/json" -d "$req_body"
  fi
  curl "$@" && echo
}
```

{% endcode %}

The `-hmac` option puts the secret on the command line, where other users of the machine can see it in the process list. Use the recipe for testing from your own machine and the Node.js or Python helper in production.
{% endtab %}

{% tab title="Node.js" %}
Requires Node.js 18 or later. The helper uses the built-in `fetch` and `crypto` modules, so there is nothing to install. Save it as `tron_energy.mjs`.

{% code title="tron\_energy.mjs" %}

```javascript
import { createHmac } from "node:crypto";

// Join METHOD, PATH, TIMESTAMP and BODY with newlines, then sign with HMAC-SHA256.
// Returns the signature as lowercase hex.
export function sign(secret, method, path, timestamp, body) {
  return createHmac("sha256", secret)
    .update([method, path, timestamp, body].join("\n"))
    .digest("hex");
}

// path is the path plus query string relative to BASE_URL,
// for example "/v1/rentals?status=reclaimed". Returns { status, data }.
export async function signedRequest(method, path, body) {
  const { BASE_URL, API_KEY, API_SECRET } = process.env;
  if (!BASE_URL || !API_KEY || !API_SECRET) {
    throw new Error("Set BASE_URL, API_KEY and API_SECRET in the environment");
  }

  const verb = method.toUpperCase();
  const payload = body === undefined ? "" : JSON.stringify(body); // serialise once
  const timestamp = String(Math.floor(Date.now() / 1000));
  const headers = {
    "X-API-Key": API_KEY,
    "X-Timestamp": timestamp,
    "X-Signature": sign(API_SECRET, verb, path, timestamp, payload),
  };
  if (payload) headers["Content-Type"] = "application/json";

  const response = await fetch(BASE_URL.replace(/\/+$/, "") + path, {
    method: verb,
    headers,
    body: payload || undefined, // the exact string that was signed
  });

  const text = await response.text();
  let data = text;
  try {
    data = JSON.parse(text);
  } catch {
    // The body is not JSON: return the text as it is
  }
  return { status: response.status, data };
}
```

{% endcode %}

Call it from any `.mjs` file:

{% code title="example.mjs" %}

```javascript
import { signedRequest } from "./tron_energy.mjs";

// GET: the query string is part of the signed path
const list = await signedRequest("GET", "/v1/rentals?status=reclaimed&limit=50");
console.log(list.status, list.data);

// POST: the body is serialised once, signed and sent as the same string
const estimate = await signedRequest("POST", "/v1/estimate", {
  from: "TJdhGqPPUGMhLWxZdMU87f7muvoN14LPpg",
  to: "TDyfoQmyKQoimRXgKfGsK94JBpZh2aVe3Y",
  token: "USDT",
  amount: "10000000",
});
console.log(estimate.status, estimate.data);
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
Requires Python 3.9 or later and `requests` (`pip install requests`). Save the helper as `tron_energy.py`.

{% code title="tron\_energy.py" %}

```python
import hashlib
import hmac
import json
import os
import time

import requests

def sign(secret, method, path, timestamp, body):
    """Sign METHOD, PATH, TIMESTAMP and BODY joined by newlines. Returns lowercase hex."""
    key = secret.encode("utf-8")
    message = "\n".join([method, path, timestamp, body]).encode("utf-8")
    return hmac.new(key, message, hashlib.sha256).hexdigest()

def signed_request(method, path, body=None):
    """Send a signed request and return (status, data).

    path is the path plus query string relative to BASE_URL,
    for example "/v1/rentals?status=reclaimed".
    """
    base_url = os.environ["BASE_URL"].rstrip("/")
    api_key = os.environ["API_KEY"]
    api_secret = os.environ["API_SECRET"]

    method = method.upper()
    payload = "" if body is None else json.dumps(body, separators=(",", ":"))  # serialise once
    timestamp = str(int(time.time()))
    headers = {
        "X-API-Key": api_key,
        "X-Timestamp": timestamp,
        "X-Signature": sign(api_secret, method, path, timestamp, payload),
    }
    if payload:
        headers["Content-Type"] = "application/json"

    response = requests.request(
        method,
        base_url + path,
        headers=headers,
        data=payload.encode("utf-8") if payload else None,  # the exact bytes that were signed
        timeout=30,
    )
    try:
        data = response.json()
    except ValueError:
        data = response.text  # The body is not JSON: return the text as it is
    return response.status_code, data
```

{% endcode %}

Call it from any Python file in the same folder:

{% code title="example.py" %}

```python
from tron_energy import signed_request

# GET: the query string is part of the signed path
status, data = signed_request("GET", "/v1/rentals?status=reclaimed&limit=50")
print(status, data)

# POST: the body is serialised once, signed and sent as the same bytes
status, data = signed_request("POST", "/v1/estimate", {
    "from": "TJdhGqPPUGMhLWxZdMU87f7muvoN14LPpg",
    "to": "TDyfoQmyKQoimRXgKfGsK94JBpZh2aVe3Y",
    "token": "USDT",
    "amount": "10000000",
})
print(status, data)
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Test vector

A test vector is a fixed secret, timestamp and request, with the signature they must produce. Until the official one is published, check your helper against the `openssl` recipe.

The three commands below sign the same dummy request, so they must print the same 64-character string. A match shows that your code builds the string described above.

<details>

<summary>Check your helper against the openssl recipe</summary>

Run these in the folder that holds `tron_energy.mjs` and `tron_energy.py`. The secret is a dummy value and the timestamp is fixed.

{% code title="check-signature.sh" %}

```bash
printf '%s\n%s\n%s\n%s' "GET" "/v1/capacity" "1793145600" "" | openssl dgst -sha256 -hmac "test-secret-not-real" | sed 's/^.* //'
node -e 'import("./tron_energy.mjs").then((m) => console.log(m.sign("test-secret-not-real", "GET", "/v1/capacity", "1793145600", "")))'
python3 -c 'from tron_energy import sign; print(sign("test-secret-not-real", "GET", "/v1/capacity", "1793145600", ""))'
```

{% endcode %}

</details>

## Troubleshooting 401 errors

Every authentication failure returns `401 UNAUTHORIZED` with the same code, so check the causes below in order.

| Cause                               | What goes wrong                                                                                                      | Fix                                                                         |
| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| Clock drift                         | `X-Timestamp` is more than 30 seconds from our clock                                                                 | Synchronise the server clock with NTP and read the clock for each request   |
| Timestamp in milliseconds           | `Date.now()` and `System.currentTimeMillis()` return milliseconds                                                    | Send whole seconds, for example `Math.floor(Date.now() / 1000)`             |
| Body differs from the signed string | The body was re-serialised after signing, with different spacing or key order, or gained a trailing newline          | Serialise once, then sign and send that same string                         |
| Query string left out of the path   | You signed `/v1/rentals` and sent `/v1/rentals?status=reclaimed`                                                     | Sign the path with its query string, in the order you send it               |
| Full URL signed                     | You signed `https://host/v1/rentals` instead of the path                                                             | Sign the path only, starting with `/v1/`                                    |
| Body signed on a `GET`              | The string holds a body for a request that sends none                                                                | Use an empty `BODY` for `GET`                                               |
| Wrong separator                     | `\r\n` instead of `\n`, or a `GET` string that lost the newline after the timestamp                                  | Join with `\n` only. A `GET` string ends with the newline after `TIMESTAMP` |
| Lower-case method                   | You signed `post` and sent `POST`                                                                                    | Use the upper-case method in the string and in the request                  |
| Signature encoding                  | Base64, upper-case hex or raw bytes                                                                                  | Send lowercase hex                                                          |
| Wrong key or secret                 | A misspelt header name, a space or newline copied with the secret, or a key and secret that were not issued together | Check the header names, trim the values and use the pair we issued together |

If a request still fails, contact our team with the `request_id` from the error body, the method and path you signed and the timestamp you sent. Never send your secret. [Getting access](https://docs.luganodes.com/tron-energy/getting-access.md) lists how to reach us.

## Handling credentials

* Store the API key and secret in a secrets manager or in environment variables on your servers.
* Call the API from your backend only, not from browsers or mobile apps. Any client that signs requests holds the secret.
* The secret signs every request and is never sent with it. Keep it out of source control, logs and error reports.
* Credentials can be rotated on request. [Getting access](https://docs.luganodes.com/tron-energy/getting-access.md) explains how credentials are issued.

## Next steps

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Errors</strong></td><td>The error format, every code, and whether to retry.</td><td><a href="https://docs.luganodes.com/tron-energy/energy-rental-api/errors.md">Errors</a></td></tr></tbody></table>
