Due to their interesting features, blockchains have become popular in recent years. They are full-stack systems where security is a critical factor for their success. The main focus of this work is to systematize knowledge about security and privacy issues of blockchains. To this end, we propose a security reference architecture based on models that demonstrate the stacked hierarchy of various threats (similar to the ISO/OSI hierarchy) as well as threat-risk assessment using ISO/IEC 15408. In contrast to the previous surveys, we focus on the categorization of security incidents based on their origins and using the proposed architecture we present existing prevention and mitigation techniques. The scope of our work mainly covers aspects related to the decentralized nature of blockchains, while we mention common operational security issues and countermeasures only tangentially.