topshef / katomia

0 stars 0 forks source link

hedera entity checksum #1

Open topshef opened 1 year ago

topshef commented 1 year ago

https://github.com/hashgraph/hedera-improvement-proposal/blob/master/assets/hip-15/HIP-15-javascript.html

topshef commented 1 year ago
  0 = mainnet
  1 = stable testnet
  2 = previewnet
topshef commented 1 year ago

https://kpos.uk/katomic/checksum.html

topshef commented 1 year ago

this is a fairly straightforward feature add, but not critical path for demo

topshef commented 1 month ago

https://github.com/hashgraph/hedera-improvement-proposal/blob/main/assets%2Fhip-15%2FHIP-15-pseudocode.md

topshef commented 1 month ago

try this

function hederaChecksum(account, ledgerId = 0) {
  const p3 = 26 * 26 * 26
  const p5 = 26 * 26 * 26 * 26 * 26
  const alphabet = 'abcdefghijklmnopqrstuvwxyz'

  // Convert the account string into an integer array where "." is represented as 10
  let d = []
  for (let ch of account) {
    if (ch === '.') d.push(10)
    else d.push(parseInt(ch))
  }

  // Convert the ledger ID to a byte array and append 6 zero bytes
  let h = [ledgerId].concat(Array(6).fill(0))

  // Calculate weighted sums
  let sd0 = d.filter((_, i) => i % 2 === 0).reduce((acc, val) => acc + val, 0) % 11
  let sd1 = d.filter((_, i) => i % 2 !== 0).reduce((acc, val) => acc + val, 0) % 11

  // Calculate sd (weighted sum of digits mod p3)
  let sd = d[0]
  for (let i = 1; i < d.length; i++)
    sd = (sd * 31 + d[i]) % p3

  // Calculate sh (weighted sum of ledger ID mod p5)
  let sh = h[0]
  for (let i = 1; i < h.length; i++)
    sh = (sh * 31 + h[i]) % p5

  // Combine all the parts to form the checksum
  let c = (((d.length % 5) * 11 + sd0) * 11 + sd1) * p3 + sd + sh
  let cp = (c * 1000003) % p5

  // Convert the result to base-26 to get 5 letters
  let checksum = ''
  for (let i = 0; i < 5; i++) {
    checksum = alphabet[cp % 26] + checksum
    cp = Math.floor(cp / 26)
  }

  return checksum
}

// Example usage for account "0.0.27500" on ledger ID 0 (mainnet)
let account = "0.0.27500"
let checksum = hederaChecksum(account)
console.log(`${account}-${checksum}`)