2021-11-05 11:57:06 +00:00
|
|
|
local _M = {}
|
|
|
|
|
2021-11-05 14:32:32 +00:00
|
|
|
local basexx = require("basexx")
|
2021-12-20 10:27:29 +00:00
|
|
|
local hasher = require("hasher")
|
2021-11-05 11:57:06 +00:00
|
|
|
|
2022-03-03 21:04:55 +00:00
|
|
|
-- use lowercase alphabet since our skylinks are part of urls
|
|
|
|
local base32_alphabet = "0123456789abcdefghijklmnopqrstuv"
|
|
|
|
|
2021-11-05 11:57:06 +00:00
|
|
|
-- parse any skylink and return base64 version
|
2022-03-03 21:04:55 +00:00
|
|
|
function _M.base64(skylink)
|
2021-11-05 11:57:06 +00:00
|
|
|
if string.len(skylink) == 55 then
|
2022-03-03 21:04:55 +00:00
|
|
|
local decoded = basexx.from_basexx(string.lower(skylink), base32_alphabet, 5)
|
2021-11-05 11:57:06 +00:00
|
|
|
|
2021-11-05 14:32:32 +00:00
|
|
|
return basexx.to_url64(decoded)
|
2021-11-05 11:57:06 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
return skylink
|
|
|
|
end
|
|
|
|
|
2022-03-03 21:04:55 +00:00
|
|
|
-- parse any skylink and return base32 version
|
|
|
|
function _M.base32(skylink)
|
|
|
|
if string.len(skylink) == 46 then
|
|
|
|
local decoded = basexx.from_url64(skylink)
|
|
|
|
|
|
|
|
return basexx.to_basexx(decoded, base32_alphabet, 5)
|
|
|
|
end
|
|
|
|
|
|
|
|
return skylink
|
|
|
|
end
|
|
|
|
|
2021-12-20 10:27:29 +00:00
|
|
|
-- hash skylink into 32 bytes hash used in blocklist
|
|
|
|
function _M.hash(skylink)
|
|
|
|
-- ensure that the skylink is base64 encoded
|
2022-03-03 21:04:55 +00:00
|
|
|
local base64Skylink = _M.base64(skylink)
|
2021-12-20 10:27:29 +00:00
|
|
|
|
|
|
|
-- decode skylink from base64 encoding
|
|
|
|
local rawSkylink = basexx.from_url64(base64Skylink)
|
|
|
|
|
|
|
|
-- drop first two bytes and leave just merkle root
|
|
|
|
local rawMerkleRoot = string.sub(rawSkylink, 3)
|
|
|
|
|
|
|
|
-- parse with blake2b with key length of 32
|
|
|
|
local blake2bHashed = hasher.blake2b(rawMerkleRoot, 32)
|
|
|
|
|
|
|
|
-- hex encode the blake hash
|
|
|
|
local hexHashed = basexx.to_hex(blake2bHashed)
|
|
|
|
|
|
|
|
-- lowercase the hex encoded hash
|
|
|
|
local lowerHexHashed = string.lower(hexHashed)
|
|
|
|
|
|
|
|
return lowerHexHashed
|
|
|
|
end
|
|
|
|
|
2021-11-05 11:57:06 +00:00
|
|
|
return _M
|