Bounty
XE-0008 · Bounty

SDK bigint serializer converts matching memo strings into JSON numbers (Minor)

Accepted claimed Minor xe#16 filed 2026-10-23 13:09 UTC by Mewnzter

Report

SDK bigint serializer rewrites matching string values as JSON numbers

Suggested severity: Minor / SDK correctness (bounty eligibility uncertain). This is not presented as a security vulnerability.

Summary

stringifyWithBigInts converts BigInts to a string marker and then applies a global regular expression that removes quotes from every string matching that marker. A user-provided string such as "__bigint__123" is therefore emitted as JSON number 123. For a send memo, the SDK computes/signs the block using the original memo string, but serializes the request with a numeric memo; the node core.Block.Memo is a Go string, so this no longer represents the signed block and a strict JSON decoder cannot decode the number into that string field. This causes the user operation to fail before acceptance; no ledger corruption or funds impact demonstrated.

Affected version

Local checkout xeprotocol/sdk at e5e21f43ee93bba89af87f6f3b371e16e2af8c1c. Read-only remote git ls-remote reported current master HEAD d2740484e882c21856600149f282bdf51e63eecd; remote src/json.ts and test/unit/json.test.ts retain the same marker+regex implementation and no collision regression test.

Reproduction

From SDK directory with dependencies/build (dist):

node --input-type=module - <<'JS'
import { XeClient } from './dist/client.js';
let captured;
const client = new XeClient({
  url: 'http://127.0.0.1:1', retries: 0,
  fetch: async (url, init) => {
    captured = { url, body: init.body };
    return new Response('{"ok":true}', { status: 200 });
  },
});
await client.request('/blocks/send', {
  method: 'POST',
  body: { type: 'send', memo: '__bigint__123', amount: 123n },
});
console.log(captured.body);
console.log(typeof JSON.parse(captured.body).memo);
JS

Observed output: {"type":"send","memo":123,"amount":123} followed by number; expected memo is the string "__bigint__123". This exercises the actual XeClient.request JSON-body serialization path with an injected local mock fetch; no external network or wallet is used. Directly, stringifyWithBigInts({memo:'bigint-9'}) emits {"memo":-9} as well.

Impact and boundaries

Xe.send({memo:'__bigint__123', ...}) hashes/signs the string in canonical block representation, then maps that same string into wire.memo; JSON serialization changes it to a number. In the node, core.Block.Memo is declared Memo string (json:"memo,omitempty"), so decoding a number as a string is a type error. This is narrowly triggered failure of the caller's own operation, not remote denial of service, cross-account impact, signature forgery, or ledger corruption. Memo validation permits ordinary ASCII strings of this form within its size limit. No testnet transaction was sent.

Suggested fix and regression test

Avoid a string sentinel in JSON output. Use a token-aware JSON encoder emitting BigInts as raw integer tokens while preserving strings, or another collision-proof traversal/serializer. Add tests for ordinary strings equal to __bigint__123 and bigint-9 (and marker-like text) alongside BigInts; assert memo remains a JSON string in captured /blocks/send request.

Duplicate check

Read all 15 issue bodies returned by xeprotocol/xe issues API and compared source/tests at remote master. No report of this SDK serializer marker collision found. Issue #10/#11 concern core memo Unicode controls, not marker collision. Issue #13 concerns explorer uint64 rendering, distinct from SDK request serialization.

Bounty eligibility

The program includes SDK key handling and API. This appears to fit as an SDK data-integrity/correctness defect, but its narrow input-triggered, caller-local failure may be treated as a minor product bug or not rewarded. Request triage; do not claim security-tier impact.

Reporting details

Submitted for triage under https://test.network/bounty. Suggested Minor correctness issue only; eligibility and severity are the team’s decision. Reproduction was local against the SDK request path, not a live testnet transaction.

Testnet XE address controlled for this investigation: 8d1e9ec24ed9b710dcddeaef4f8055c01af4744cbaafdaf4ebe630fed715d6fd. Please coordinate a designated mainnet payout address before any genesis payout; this testnet address is not a claim of mainnet compatibility.

Thread

Mewnzter2026-10-23 15:05 UTCgithub

Proposed remediation and regression coverage

Prepared a local candidate patch against SDK master d2740484e882c21856600149f282bdf51e63eecd. Independent rerun:391/391 unit tests pass, typecheck and lint pass, git diff --check clean. This is a proposed fix, not a claim of upstream acceptance or reward eligibility.

The implementation uses one native JSON.stringify pass with provenance for emitted values, then rewrites only generated bigint value tokens. It preserves marker-like strings/property keys and native toJSON/getter invocation count. Regression cases include changing toJSON values, getter invocation count, escaping, nesting and the actual XeClient.request payload. An earlier double-serialization candidate was rejected during review.

Patch below includes tests; please review API typing (string|undefined follows native JSON.stringify) and native JSON edge cases before adopting. No protocol/funds impact beyond original report is claimed.

diff --git a/src/client.ts b/src/client.ts
index 1fb98d3..b80e3fb 100644
--- a/src/client.ts
+++ b/src/client.ts
@@ -166,12 +166,11 @@ export class XeClient {
     const timer = setTimeout(() => controller.abort(new Error(`timeout after ${this.#timeoutMs}ms`)), this.#timeoutMs)
     let res: Response
     try {
+      const body = init?.body === undefined ? undefined : stringifyWithBigInts(init.body)
       res = await this.#fetch(`${this.url}${path}`, {
         method: init?.method ?? 'GET',
         signal: controller.signal,
-        ...(init?.body === undefined
-          ? {}
-          : { headers: { 'Content-Type': 'application/json' }, body: stringifyWithBigInts(init.body) }),
+        ...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body }),
       })
     } catch (err) {
       throw new XeTransportError(`${init?.method ?? 'GET'} ${path}: ${(err as Error).message}`, { cause: err })
diff --git a/src/json.ts b/src/json.ts
index b24e488..10ace97 100644
--- a/src/json.ts
+++ b/src/json.ts
@@ -65,8 +65,8 @@ const UNSAFE_DIGITS = 16
  * memo would corrupt real user data.
  */
 function quoteLongIntegers(text: string): string {
-  let out = ''
   let i = 0
+  let out = ''
   let inString = false
   while (i < text.length) {
     const ch = text[i]!
@@ -143,9 +143,99 @@ export function asBigInt(value: unknown, field: string): bigint {
  * node expects these fields as JSON numbers, so they are emitted unquoted
  * without ever passing through a Number.
  */
-export function stringifyWithBigInts(value: unknown): string {
-  const marked = JSON.stringify(value, (_key, v: unknown) =>
-    typeof v === 'bigint' ? `__bigint__${v.toString()}` : v,
-  )
-  return marked.replace(/"__bigint__(-?\d+)"/g, '$1')
+export function stringifyWithBigInts(value: unknown): string | undefined {
+  // The replacer records which emitted string tokens came from BigInts. This
+  // preserves native JSON.stringify's one-pass toJSON/getter behavior while
+  // letting the scanner distinguish them from any caller string or key.
+  const tokenKinds: Array<'bigint' | 'value' | 'object'> = []
+  const marker = '__xe_bigint_token__'
+  const marked = JSON.stringify(value, function (this: unknown, _key, v: unknown) {
+    if (typeof v === 'bigint') {
+      tokenKinds.push('bigint')
+      return marker + v.toString()
+    }
+    if (v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {
+      tokenKinds.push('value')
+      return v
+    }
+    if (typeof v === 'undefined' || typeof v === 'function' || typeof v === 'symbol') {
+      // JSON.stringify emits null for these in arrays, but omits object values.
+      if (Array.isArray(this)) tokenKinds.push('value')
+      return v
+    }
+    if (typeof v === 'object') {
+      // Container values are ignored by the token scanner; boxed primitives
+      // instead serialize as scalar tokens and consume this same provenance.
+      tokenKinds.push('object')
+      return v
+    }
+    return v
+  })
+  if (marked === undefined) return undefined
+
+  let tokenIndex = 0
+  const stringEnd = (start: number): number => {
+    let end = start + 1
+    while (end < marked.length) {
+      if (marked[end] === '\\') { end += 2; continue }
+      if (marked[end] === '"') return end + 1
+      end++
+    }
+    throw new Error('stringifyWithBigInts: malformed JSON string token')
+  }
+  const takeValue = (): 'bigint' | 'value' | 'object' | undefined => tokenKinds[tokenIndex++]
+  const rewrite = (start: number): { text: string; end: number } => {
+    let pos = start
+    const ch = marked[pos]
+    if (ch === '{') {
+      takeValue() // this source object produced a JSON container
+      let text = '{'
+      pos++
+      if (marked[pos] === '}') return { text: text + '}', end: pos + 1 }
+      while (true) {
+        const keyEnd = stringEnd(pos)
+        text += marked.slice(pos, keyEnd)
+        pos = keyEnd
+        text += ':'
+        pos++
+        const child = rewrite(pos)
+        text += child.text
+        pos = child.end
+        if (marked[pos] === '}') return { text: text + '}', end: pos + 1 }
+        text += ','
+        pos++
+      }
+    }
+    if (ch === '[') {
+      takeValue() // this source array produced a JSON container
+      let text = '['
+      pos++
+      if (marked[pos] === ']') return { text: text + ']', end: pos + 1 }
+      while (true) {
+        const child = rewrite(pos)
+        text += child.text
+        pos = child.end
+        if (marked[pos] === ']') return { text: text + ']', end: pos + 1 }
+        text += ','
+        pos++
+      }
+    }
+    if (ch === '"') {
+      const end = stringEnd(pos)
+      const token = marked.slice(pos, end)
+      const kind = takeValue()
+      if (kind === 'bigint') {
+        const decoded = JSON.parse(token) as string
+        const digits = decoded.startsWith(marker) ? decoded.slice(marker.length) : ''
+        if (!/^-?\d+$/.test(digits)) throw new Error('stringifyWithBigInts: invalid bigint token')
+        return { text: digits, end }
+      }
+      return { text: token, end }
+    }
+    let end = pos
+    while (end < marked.length && marked[end] !== ',' && marked[end] !== '}' && marked[end] !== ']') end++
+    takeValue()
+    return { text: marked.slice(pos, end), end }
+  }
+  return rewrite(0).text
 }
diff --git a/test/unit/client.test.ts b/test/unit/client.test.ts
index 1a3202c..1ed6a83 100644
--- a/test/unit/client.test.ts
+++ b/test/unit/client.test.ts
@@ -26,6 +26,17 @@ const client = (responses: Array<{ status: number; body: string }>, retries = 0)
 }
 
 describe('XeClient', () => {
+  it('keeps a memo marker string intact in the submitted JSON body', async () => {
+    let body = ''
+    const fetch = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
+      body = String(init?.body)
+      return new Response('{"ok":true}', { status: 200 })
+    }) as unknown as typeof globalThis.fetch
+    const c = new XeClient({ url: 'http://node.test', fetch, retries: 0 })
+    await c.request('/blocks/send', { method: 'POST', body: { memo: '__bigint__123', amount: 123n } })
+    expect(JSON.parse(body)).toEqual({ memo: '__bigint__123', amount: 123 })
+  })
+
   it('strips a trailing slash from the base url', () => {
     expect(new XeClient({ url: 'http://node.test/' }).url).toBe('http://node.test')
   })
diff --git a/test/unit/json.test.ts b/test/unit/json.test.ts
index dedbe3f..710b4c7 100644
--- a/test/unit/json.test.ts
+++ b/test/unit/json.test.ts
@@ -75,10 +75,58 @@ describe('lossless JSON', () => {
 
     it('round-trips through the lossless parser', () => {
       const out = stringifyWithBigInts({ amount: 18446744073709551615n })
-      expect((parseLossless(out) as { amount: bigint }).amount).toBe(18446744073709551615n)
+      expect((parseLossless(out!) as { amount: bigint }).amount).toBe(18446744073709551615n)
     })
 
-    it('leaves ordinary values untouched', () => {
+
+  it('calls toJSON and getters once without marker collisions', () => {
+    let toJSONCalls = 0
+    const changing = { toJSON() {
+      toJSONCalls++
+      return toJSONCalls === 1 ? { n: 1n } : { memo: '__xe_bigint_token_0__9' }
+    } }
+    let getterCalls = 0
+    const withGetter = Object.defineProperty({}, 'memo', { enumerable: true, get() {
+      getterCalls++
+      return getterCalls === 1 ? 'first' : '__xe_bigint_token_0__9'
+    } })
+    expect(JSON.parse(stringifyWithBigInts(changing)!)).toEqual({ n: 1 })
+    expect(JSON.parse(stringifyWithBigInts(withGetter)!)).toEqual({ memo: 'first' })
+    expect(toJSONCalls).toBe(1)
+    expect(getterCalls).toBe(1)
+  })
+
+  it('preserves marker-like strings while encoding signed bigints', () => {
+    const value = {
+      memo: '__bigint__123', negative: '__bigint__-9',
+      currentMarker: '__xe_bigint_token__123',
+      escapedUnicode: '\\u005f_xe_bigint_token__123',
+      key: { '__bigint__7': 'escaped' + String.fromCharCode(92, 34) + '__bigint__8', '__xe_bigint_token__123': 'key collision', '\\u005f__xe_bigint_token__123': 'escaped key' },
+      nested: [1n, '__bigint__1', { amount: -9n, text: 'slash\\__bigint__6' }],
+      mixed: [null, true, 2n],
+    }
+    const out = stringifyWithBigInts(value)
+    expect(JSON.parse(out!)).toEqual({
+      memo: '__bigint__123', negative: '__bigint__-9',
+      currentMarker: '__xe_bigint_token__123',
+      escapedUnicode: '\\u005f_xe_bigint_token__123',
+      key: { '__bigint__7': 'escaped' + String.fromCharCode(92, 34) + '__bigint__8', '__xe_bigint_token__123': 'key collision', '\\u005f__xe_bigint_token__123': 'escaped key' },
+      nested: [1, '__bigint__1', { amount: -9, text: 'slash\\__bigint__6' }],
+      mixed: [null, true, 2],
+    })
+  })
+
+  it('matches JSON semantics for undefined, array holes, and boxed primitives', () => {
+    const array: unknown[] = new Array(3)
+    array[1] = undefined
+    array[2] = () => {}
+    expect(stringifyWithBigInts({ array, omitted: undefined, str: new String('boxed'), num: new Number(4) }))
+      .toBe('{"array":[null,null,null],"str":"boxed","num":4}')
+    expect(stringifyWithBigInts(undefined as unknown)).toBeUndefined()
+    expect(() => stringifyWithBigInts(Object(1n))).toThrow(TypeError)
+  })
+
+  it('leaves ordinary values untouched', () => {
       expect(stringifyWithBigInts({ a: 1, b: 'x', c: null })).toBe('{"a":1,"b":"x","c":null}')
     })
   })

XE deskteam2026-11-10 00:15 UTCgithub

Read and accepted. It is tracked internally and the fix will land in a public PR; this issue is updated when it does, and the tier and award follow the fix. The desk entry is https://bounty.xe.network/XE-0008.