local chacha = require 'chacha'

local key = string.char(
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
)
local iv = string.char(0, 0, 0, 0, 0, 0, 0, 0)
local expect0 = string.char(
   0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90,
   0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28,
   0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a,
   0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7,
   0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d,
   0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37,
   0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c,
   0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86
)
local expect1 = string.char(
   0x9f, 0x07, 0xe7, 0xbe, 0x55, 0x51, 0x38, 0x7a,
   0x98, 0xba, 0x97, 0x7c, 0x73, 0x2d, 0x08, 0x0d,
   0xcb, 0x0f, 0x29, 0xa0, 0x48, 0xe3, 0x65, 0x69,
   0x12, 0xc6, 0x53, 0x3e, 0x32, 0xee, 0x7a, 0xed,
   0x29, 0xb7, 0x21, 0x76, 0x9c, 0xe6, 0x4e, 0x43,
   0xd5, 0x71, 0x33, 0xb0, 0x74, 0xd8, 0x39, 0xd5,
   0x31, 0xed, 0x1f, 0x28, 0x51, 0x0a, 0xfb, 0x45,
   0xac, 0xe1, 0x0a, 0x1f, 0x4b, 0x79, 0x4d, 0x6f
)

local function show(block)
    for i = 1, #block do
        local byte = string.byte(block, i)
        local sep = string.byte('\n               ', i % 16 + 1)
        local hex = string.format('%02x%c', byte, sep)
        io.output():write(hex)
    end
end

local state = chacha.new(key, iv)
local out0 = chacha.generate(state)
local out1 = chacha.generate(state)
local fail = false

if out0 ~= expect0 then
    print('Output 0:')
    show(out0)
    print('Expect 0:')
    show(expect0)
    fail = true
end
if out1 ~= expect1 then
    print('Output 1:')
    show(out1)
    print('Expect 1:')
    show(expect1)
    fail = true
end

if fail then
    print('FAIL')
    os.exit(1)
else
    print('PASS')
    os.exit(0)
end
