Mostly taken from old SDK (abe47687cd11266f946cad57f07572cc10c67226), but error handling adapted to eliminate pkg/errors and internal packages. Signed-off-by: Roman Khimov <roman@nspcc.ru>